mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-20 07:39:54 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6e9cf8dfb6 | ||
|
|
d2620f6911 | ||
|
|
4537baa6a2 | ||
|
|
810e0c4cf5 | ||
|
|
07cb648183 | ||
|
|
c6602c9f1c | ||
|
|
86032539ed | ||
|
|
b2ec012e10 | ||
|
|
7fd8623684 | ||
|
|
083753a96d | ||
|
|
4b62c31f29 | ||
|
|
2208d4e0e0 | ||
|
|
df7f4c3c2d | ||
|
|
12323e1416 | ||
|
|
2edc5e1071 | ||
|
|
2162ed9ebe | ||
|
|
6acebb73ec | ||
|
|
7a1d6c0ab5 | ||
|
|
d16e31c0e5 | ||
|
|
d9a8b6a191 | ||
|
|
5ec4cd7fcd | ||
|
|
a7925e3c79 | ||
|
|
472b420620 | ||
|
|
8f55ba1d37 | ||
|
|
7b1428bf51 | ||
|
|
d5b3b1868e | ||
|
|
49f3fc0be5 | ||
|
|
59e641ccb3 | ||
|
|
1d9268b224 | ||
|
|
470a4bd6f7 | ||
|
|
8801d59b2e | ||
|
|
6a20e06982 | ||
|
|
b17abce2c2 | ||
|
|
f67e334016 | ||
|
|
c1de66520e | ||
|
|
37e086d822 | ||
|
|
d21f8ca8de | ||
|
|
6af4e7c2ec | ||
|
|
1f2bdc8c9e | ||
|
|
4c0fd29b7f | ||
|
|
ffef67be8f | ||
|
|
4d100bf542 | ||
|
|
8a75d015a1 | ||
|
|
f806272c06 | ||
|
|
4935eeff28 | ||
|
|
eed0264b9c | ||
|
|
dd82daf65c | ||
|
|
55d9596835 | ||
|
|
cb1c1c502b | ||
|
|
6d4f62d6f6 | ||
|
|
43808216e6 | ||
|
|
f66bb7af73 | ||
|
|
ae86d56a7d | ||
|
|
1cee103b1c | ||
|
|
3c3b6880e4 |
@@ -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,13 @@
|
||||
</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 href="https://hub.docker.com/r/shumaione/shumai"><img alt="Docker pulls" src="https://img.shields.io/docker/pulls/shumaione/shumai" /></a>
|
||||
<a href="https://github.com/shumaiOne/shumai/releases"><img alt="GitHub latest release" src="https://img.shields.io/github/v/release/shumaiOne/shumai" /></a>
|
||||
<a href="LICENSE"><img alt="License" src="https://img.shields.io/badge/license-MIT-blue" /></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<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 +43,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 +51,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]
|
||||
|
||||
+14
-1
@@ -9,8 +9,13 @@
|
||||
</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 href="https://hub.docker.com/r/shumaione/shumai"><img alt="Docker pulls" src="https://img.shields.io/docker/pulls/shumaione/shumai" /></a>
|
||||
<a href="https://github.com/shumaiOne/shumai/releases"><img alt="GitHub latest release" src="https://img.shields.io/github/v/release/shumaiOne/shumai" /></a>
|
||||
<a href="LICENSE"><img alt="License" src="https://img.shields.io/badge/license-MIT-blue" /></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<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>
|
||||
|
||||

|
||||
@@ -38,11 +43,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.7",
|
||||
"version": "0.4.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"bin": {
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
export * from '@shumai/agent/src/workflows/agent-autofill'
|
||||
export * from '@shumai/agent/src/workflows/agent-chat'
|
||||
export * from '@shumai/agent/src/workflows/agent-embedding'
|
||||
export * from '@shumai/agent/src/workflows/agent-tool-call'
|
||||
export * from '@shumai/agent/src/workflows/query-embedding-for-search'
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/cli",
|
||||
"version": "0.3.7",
|
||||
"version": "0.4.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"bin": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/transcode-app",
|
||||
"version": "0.3.7",
|
||||
"version": "0.4.1",
|
||||
"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 |
|
||||
@@ -80,12 +83,17 @@ apps/web/e2e/
|
||||
| Owner drags a file into a folder and a folder into another folder | `tests/project/move-folder-file.spec.ts` |
|
||||
| Owner drags a file onto a file to create a version stack | `tests/project/version-stack-create.spec.ts` |
|
||||
| Owner drags a file onto a version stack to add a new version | `tests/project/version-stack-add-version.spec.ts` |
|
||||
| Owner manages version stack: removes version from 3-version stack | `tests/project/version-stack-manage.spec.ts` |
|
||||
| Owner removes version from 2-version stack which dissolves into standalone files | `tests/project/version-stack-manage.spec.ts` |
|
||||
| Dissolving a shared version stack renders the remaining standalone file name on the share page | `tests/project/version-stack-manage.spec.ts` |
|
||||
| Moving a shared file into a shared version stack leaves only 1 stack card on the share page | `tests/project/version-stack-manage.spec.ts` |
|
||||
| Owner searches the file list by an English name keyword | `tests/project/search-file-list.spec.ts` |
|
||||
| Owner searches the file list by Chinese, Japanese, and Korean name keywords | `tests/project/search-file-list.spec.ts` |
|
||||
| Owner searches the file list with a keyword and a filter condition | `tests/project/search-file-list.spec.ts` |
|
||||
| Owner saves a search result as a collection | `tests/project/save-search-collection.spec.ts` |
|
||||
| Image share with watermark + download disabled: no download buttons on public list/detail pages, watermarked proxy served, download-url rejected | `tests/project/share-watermark-no-download.spec.ts` |
|
||||
| Video share with watermark + download disabled: no download buttons on public list/detail pages, watermarked proxy served, download-url rejected | `tests/project/share-watermark-no-download.spec.ts` |
|
||||
| Owner views a file and it appears in recents | `tests/project/recents.spec.ts` |
|
||||
|
||||
### file
|
||||
| Test | File |
|
||||
|
||||
+16
-11
@@ -21,19 +21,23 @@ const currentDir = path.dirname(fileURLToPath(import.meta.url))
|
||||
const envPath = path.resolve(currentDir, '.env.e2e')
|
||||
const fixturesDir = path.resolve(currentDir, '../../../packages/e2e/fixtures')
|
||||
|
||||
// Load E2E environment variables if present
|
||||
if (fs.existsSync(envPath)) {
|
||||
const content = fs.readFileSync(envPath, 'utf8')
|
||||
content.split('\n').forEach((line) => {
|
||||
const parts = line.split('=')
|
||||
if (parts.length >= 2) {
|
||||
const key = parts[0].trim()
|
||||
const value = parts.slice(1).join('=').trim()
|
||||
process.env[key] = value
|
||||
}
|
||||
})
|
||||
function loadEnv() {
|
||||
if (fs.existsSync(envPath)) {
|
||||
const content = fs.readFileSync(envPath, 'utf8')
|
||||
content.split('\n').forEach((line) => {
|
||||
const parts = line.split('=')
|
||||
if (parts.length >= 2) {
|
||||
const key = parts[0].trim()
|
||||
const value = parts.slice(1).join('=').trim()
|
||||
process.env[key] = value
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Load E2E environment variables if present
|
||||
loadEnv()
|
||||
|
||||
export interface OwnerFixture {
|
||||
/** Page opened in a browser context logged in as the team owner. */
|
||||
page: Page
|
||||
@@ -104,6 +108,7 @@ export const test = base.extend<{
|
||||
prisma: [
|
||||
// eslint-disable-next-line no-empty-pattern
|
||||
async ({}, use) => {
|
||||
loadEnv()
|
||||
const connectionString = process.env.DATABASE_URL
|
||||
const pool = new Pool({ connectionString })
|
||||
const adapter = new PrismaPg(pool)
|
||||
|
||||
@@ -7,15 +7,16 @@ interface CreateShareResponse {
|
||||
}
|
||||
|
||||
/**
|
||||
* Locates a file/folder card by its name. File names are rendered as
|
||||
* `EditableText` inputs (not text nodes), so `getByText` does not match them.
|
||||
* The returned locator points at the card wrapper div (right-clickable to open
|
||||
* the card context menu).
|
||||
* Locates a file/folder card by its name. Matches both read-only text nodes
|
||||
* and active EditableText inputs. The returned locator points at the card
|
||||
* wrapper div (right-clickable to open the card context menu).
|
||||
*/
|
||||
export function fileCard(page: Page, name: string): Locator {
|
||||
return page
|
||||
.locator('div.group')
|
||||
.filter({ has: page.locator(`input[value="${name}"]`) })
|
||||
.filter({
|
||||
has: page.locator(`input[value="${name}"]`).or(page.getByText(name, { exact: true })),
|
||||
})
|
||||
.first()
|
||||
}
|
||||
|
||||
|
||||
@@ -32,4 +32,7 @@ async function start() {
|
||||
await import('../src/index.ts')
|
||||
}
|
||||
|
||||
start().catch(console.error)
|
||||
start().catch((err) => {
|
||||
console.error('Failed to start E2E server:', err)
|
||||
process.exit(1)
|
||||
})
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import { expect, test } from '../../fixtures'
|
||||
import { apiSignup, E2E_PASSWORD, uniqueEmail } from '../../helpers/auth'
|
||||
import { loginViaUi } from '../../helpers/ui'
|
||||
|
||||
test('should show error when accessing reset-password page without token', async ({ page }) => {
|
||||
await page.goto('/reset-password')
|
||||
await expect(page.getByText('Invalid or missing reset token.')).toBeVisible()
|
||||
await expect(page.getByRole('button', { name: 'Go to Login' })).toBeVisible()
|
||||
})
|
||||
|
||||
test('should reset password with valid token and allow logging in with new password', async ({
|
||||
page,
|
||||
request,
|
||||
prisma,
|
||||
}) => {
|
||||
const email = uniqueEmail('reset-pw')
|
||||
const oldPassword = E2E_PASSWORD
|
||||
const newPassword = 'newSecretPassword123'
|
||||
|
||||
// 1. Seed user
|
||||
await apiSignup(request, email, oldPassword)
|
||||
|
||||
// 2. Request password reset via API
|
||||
const resetRes = await request.post('/api/auth/request-password-reset', {
|
||||
data: {
|
||||
email,
|
||||
redirectTo: '/reset-password',
|
||||
},
|
||||
})
|
||||
expect(resetRes.ok()).toBe(true)
|
||||
|
||||
// Retrieve the generated verification token from DB
|
||||
const verification = await prisma.verification.findFirst({
|
||||
where: {
|
||||
identifier: { startsWith: 'reset-password:' },
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
})
|
||||
expect(verification).not.toBeNull()
|
||||
const token = verification!.identifier.replace('reset-password:', '')
|
||||
|
||||
// 3. Open reset password page with token
|
||||
await page.goto(`/reset-password?token=${token}`)
|
||||
|
||||
// 4. Fill in new password and confirmation
|
||||
await page.locator('input#password').fill(newPassword)
|
||||
await page.locator('input#confirmPassword').fill(newPassword)
|
||||
|
||||
// 5. Submit form
|
||||
await page.getByRole('button', { name: 'Reset Password' }).click()
|
||||
|
||||
// 6. Verify success state
|
||||
await expect(page.getByText('Password reset successfully!')).toBeVisible()
|
||||
|
||||
// 7. Click Go to Login
|
||||
await page.getByRole('button', { name: 'Go to Login' }).click()
|
||||
await expect(page).toHaveURL('/login')
|
||||
|
||||
// 8. Log in with the new password
|
||||
await loginViaUi(page, email, newPassword)
|
||||
await expect(page).toHaveURL(/\/teams\/[^/]+/)
|
||||
await expect(page.getByRole('heading', { name: 'Projects' })).toBeVisible()
|
||||
})
|
||||
@@ -40,8 +40,8 @@ test('owner should create a project with a cover image', async ({ owner, prisma
|
||||
await expect(page).toHaveURL(/\/projects\/[^/]+/)
|
||||
await expect(page.locator(`text=${projectName}`).first()).toBeVisible()
|
||||
|
||||
// Back on the dashboard the new project card is visible with its cover
|
||||
await page.click('button[aria-label="Dashboard"]')
|
||||
// Back on the home page the new project card is visible with its cover
|
||||
await page.click('button[aria-label="Home"]')
|
||||
await expect(page).toHaveURL(/\/teams\/[^/]+/)
|
||||
await expect(page.locator(`img[alt="${projectName}"]`)).toBeVisible()
|
||||
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { expect, test } from '../../fixtures'
|
||||
import { fileCard } from '../../helpers/files'
|
||||
|
||||
test('owner views a file and it appears in recents', async ({ file }) => {
|
||||
const { page, projectId, fileName, fileId } = file
|
||||
|
||||
// Open the file details page to record view
|
||||
await page.goto(`/projects/${projectId}/files/${fileId}`)
|
||||
await expect(page.getByText(fileName).first()).toBeVisible()
|
||||
|
||||
// Navigate to Recents page via sidebar or direct URL
|
||||
await page.goto(`/projects/${projectId}`)
|
||||
await page.getByText('Recently Viewed').first().click()
|
||||
await expect(page).toHaveURL(new RegExp(`/projects/${projectId}/recents`))
|
||||
|
||||
// The viewed file should be visible in recents
|
||||
const card = fileCard(page, fileName)
|
||||
await expect(card).toBeVisible()
|
||||
|
||||
// Toolbar should show hint text instead of action buttons
|
||||
await expect(
|
||||
page.getByText('This page displays the 100 most recent files you viewed in this project.'),
|
||||
).toBeVisible()
|
||||
await expect(page.getByRole('button', { name: 'Field' })).not.toBeVisible()
|
||||
await expect(page.getByRole('button', { name: 'Search' })).not.toBeVisible()
|
||||
await expect(page.getByText('AGENTS.md')).not.toBeVisible()
|
||||
|
||||
// Right-clicking the file should NOT show the context menu
|
||||
await card.click({ button: 'right' })
|
||||
await expect(page.getByRole('menuitem', { name: 'Delete' })).not.toBeVisible()
|
||||
await expect(page.getByRole('menuitem', { name: 'Download' })).not.toBeVisible()
|
||||
|
||||
// The per-item overflow menu must also be unavailable on the read-only Recents page.
|
||||
await expect(card.getByRole('button')).toHaveCount(0)
|
||||
})
|
||||
@@ -0,0 +1,233 @@
|
||||
import { expect, test } from '../../fixtures'
|
||||
import { seedFile } from '../../helpers/assets'
|
||||
import { dragCard } from '../../helpers/dnd'
|
||||
import { apiAddAssetsToShare, apiCreateShare, fileCard } from '../../helpers/files'
|
||||
|
||||
test('owner manages versions: removes a version from a 3-version stack', async ({
|
||||
project,
|
||||
prisma,
|
||||
}) => {
|
||||
const { page, projectId, rootFolderId } = project
|
||||
|
||||
const fileA = await seedFile(prisma, projectId, rootFolderId, `e2e-mng-a-${Date.now()}`)
|
||||
const fileB = await seedFile(prisma, projectId, rootFolderId, `e2e-mng-b-${Date.now()}`)
|
||||
const fileC = await seedFile(prisma, projectId, rootFolderId, `e2e-mng-c-${Date.now()}`)
|
||||
|
||||
await page.goto(`/projects/${projectId}`)
|
||||
await expect(fileCard(page, fileA.name)).toBeVisible()
|
||||
await expect(fileCard(page, fileB.name)).toBeVisible()
|
||||
await expect(fileCard(page, fileC.name)).toBeVisible()
|
||||
|
||||
// 1. Create a 3-version stack: B on A -> stack (v2), then C on stack -> stack (v3)
|
||||
await dragCard(page, fileCard(page, fileB.name), fileCard(page, fileA.name))
|
||||
await expect(page.getByText('v2', { exact: true })).toBeVisible()
|
||||
|
||||
await dragCard(page, fileCard(page, fileC.name), fileCard(page, fileB.name))
|
||||
await expect(page.getByText('v3', { exact: true })).toBeVisible()
|
||||
|
||||
const stack = await prisma.asset.findFirstOrThrow({
|
||||
where: { projectId, parentId: rootFolderId, type: 'version_stack' },
|
||||
})
|
||||
expect(stack.fileCount).toBe(3)
|
||||
|
||||
// 2. Navigate to file viewer for the stack
|
||||
await page.goto(`/projects/${projectId}/files/${stack.id}`)
|
||||
|
||||
// 3. Open breadcrumb menu and click "Manage versions..."
|
||||
// Click on the asset name / badge dropdown trigger
|
||||
await page.getByRole('button', { name: new RegExp(fileC.name) }).click()
|
||||
// Hover or click on Versions sub-menu trigger
|
||||
await page.getByRole('menuitem', { name: 'Versions', exact: true }).hover()
|
||||
// Click "Manage versions..."
|
||||
await page.getByRole('button', { name: /manage versions$/i }).click()
|
||||
|
||||
// 4. Verify Manage versions dialog is visible with all 3 versions
|
||||
const dialog = page.getByRole('dialog')
|
||||
await expect(dialog).toBeVisible()
|
||||
await expect(dialog.getByText('Manage versions')).toBeVisible()
|
||||
await expect(dialog.getByText(fileA.name)).toBeVisible()
|
||||
await expect(dialog.getByText(fileB.name)).toBeVisible()
|
||||
await expect(dialog.getByText(fileC.name)).toBeVisible()
|
||||
|
||||
// 5. Remove fileB from stack: hover its row and click Remove from stack
|
||||
const rowB = dialog.locator('div.group', { hasText: fileB.name })
|
||||
await rowB.hover()
|
||||
const moreButton = rowB.getByRole('button', { name: 'More options' })
|
||||
await moreButton.click()
|
||||
await page.getByRole('menuitem', { name: /remove from stack/i }).click()
|
||||
|
||||
// 6. Verify toast and that fileB is removed from dialog
|
||||
await expect(page.getByText(/version removed from stack/i)).toBeVisible()
|
||||
await expect(dialog.getByText(fileB.name)).not.toBeVisible()
|
||||
await expect(dialog.getByText(fileA.name)).toBeVisible()
|
||||
await expect(dialog.getByText(fileC.name)).toBeVisible()
|
||||
|
||||
// DB: stack now has 2 versions (fileA and fileC), and fileB is standalone in root folder
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const s = await prisma.asset.findUnique({ where: { id: stack.id } })
|
||||
return s?.fileCount
|
||||
})
|
||||
.toBe(2)
|
||||
|
||||
const updatedFileB = await prisma.asset.findUnique({ where: { id: fileB.id } })
|
||||
expect(updatedFileB?.parentId).toBe(rootFolderId)
|
||||
})
|
||||
|
||||
test('owner removes version from 2-version stack dissolving the stack into standalone files', async ({
|
||||
project,
|
||||
prisma,
|
||||
}) => {
|
||||
const { page, projectId, rootFolderId } = project
|
||||
|
||||
const fileA = await seedFile(prisma, projectId, rootFolderId, `e2e-dis-a-${Date.now()}`)
|
||||
const fileB = await seedFile(prisma, projectId, rootFolderId, `e2e-dis-b-${Date.now()}`)
|
||||
|
||||
await page.goto(`/projects/${projectId}`)
|
||||
await dragCard(page, fileCard(page, fileB.name), fileCard(page, fileA.name))
|
||||
await expect(page.getByText('v2', { exact: true })).toBeVisible()
|
||||
|
||||
const stack = await prisma.asset.findFirstOrThrow({
|
||||
where: { projectId, parentId: rootFolderId, type: 'version_stack' },
|
||||
})
|
||||
|
||||
// Open file view
|
||||
await page.goto(`/projects/${projectId}/files/${stack.id}`)
|
||||
|
||||
// Open breadcrumb menu and click "Manage versions..."
|
||||
await page.getByRole('button', { name: new RegExp(fileB.name) }).click()
|
||||
await page.getByRole('menuitem', { name: 'Versions', exact: true }).hover()
|
||||
await page.getByRole('button', { name: /manage versions$/i }).click()
|
||||
|
||||
const dialog = page.getByRole('dialog')
|
||||
await expect(dialog).toBeVisible()
|
||||
|
||||
// Remove fileB -> stack dissolves -> only fileA remains
|
||||
const rowB = dialog.locator('div.group', { hasText: fileB.name })
|
||||
await rowB.hover()
|
||||
const moreButton = rowB.getByRole('button', { name: 'More options' })
|
||||
await moreButton.click()
|
||||
await page.getByRole('menuitem', { name: /remove from stack/i }).click()
|
||||
|
||||
// Dialog should close automatically when stack dissolves
|
||||
await expect(dialog).not.toBeVisible()
|
||||
|
||||
// DB: stack asset is deleted
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const s = await prisma.asset.findUnique({ where: { id: stack.id } })
|
||||
return s === null
|
||||
})
|
||||
.toBe(true)
|
||||
|
||||
// Both fileA and fileB are now standalone files in rootFolder
|
||||
const updatedFileA = await prisma.asset.findUnique({ where: { id: fileA.id } })
|
||||
const updatedFileB = await prisma.asset.findUnique({ where: { id: fileB.id } })
|
||||
expect(updatedFileA?.parentId).toBe(rootFolderId)
|
||||
expect(updatedFileB?.parentId).toBe(rootFolderId)
|
||||
})
|
||||
|
||||
test('dissolving a shared version stack renders the remaining standalone file name on the share page', async ({
|
||||
project,
|
||||
prisma,
|
||||
}) => {
|
||||
const { page, projectId, rootFolderId } = project
|
||||
|
||||
const fileA = await seedFile(prisma, projectId, rootFolderId, `e2e-shd-a-${Date.now()}`)
|
||||
const fileB = await seedFile(prisma, projectId, rootFolderId, `e2e-shd-b-${Date.now()}`)
|
||||
|
||||
await page.goto(`/projects/${projectId}`)
|
||||
await dragCard(page, fileCard(page, fileB.name), fileCard(page, fileA.name))
|
||||
await expect(page.getByText('v2', { exact: true })).toBeVisible()
|
||||
|
||||
const stack = await prisma.asset.findFirstOrThrow({
|
||||
where: { projectId, parentId: rootFolderId, type: 'version_stack' },
|
||||
})
|
||||
|
||||
// Share the version stack
|
||||
await fileCard(page, fileB.name).click({ button: 'right' })
|
||||
await page.getByRole('menuitem', { name: 'Create Share Link' }).click()
|
||||
const toast = page.locator('[data-sonner-toast]').filter({ hasText: 'Share link created' })
|
||||
await expect(toast).toBeVisible()
|
||||
|
||||
const share = await prisma.shareLink.findFirstOrThrow({
|
||||
where: { projectId },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
})
|
||||
|
||||
// Open file viewer for the stack
|
||||
await page.goto(`/projects/${projectId}/files/${stack.id}`)
|
||||
|
||||
// Open breadcrumb menu and click "Manage versions"
|
||||
await page.getByRole('button', { name: new RegExp(fileB.name) }).click()
|
||||
await page.getByRole('menuitem', { name: 'Versions', exact: true }).hover()
|
||||
await page.getByRole('button', { name: /manage versions$/i }).click()
|
||||
|
||||
const dialog = page.getByRole('dialog')
|
||||
await expect(dialog).toBeVisible()
|
||||
|
||||
// Remove fileB -> stack dissolves -> only fileA remains
|
||||
const rowB = dialog.locator('div.group', { hasText: fileB.name })
|
||||
await rowB.hover()
|
||||
const moreButton = rowB.getByRole('button', { name: 'More options' })
|
||||
await moreButton.click()
|
||||
await page.getByRole('menuitem', { name: /remove from stack/i }).click()
|
||||
|
||||
await expect(dialog).not.toBeVisible()
|
||||
|
||||
// Navigate to public share page: verify fileA is displayed with its non-empty name
|
||||
await page.goto(`/share/${share.id}`)
|
||||
await expect(fileCard(page, fileA.name)).toBeVisible()
|
||||
await expect(fileCard(page, fileB.name)).not.toBeVisible()
|
||||
})
|
||||
|
||||
test('moving a shared file into a shared version stack leaves only 1 stack card on the share page', async ({
|
||||
project,
|
||||
prisma,
|
||||
}) => {
|
||||
const { page, projectId, rootFolderId } = project
|
||||
|
||||
const fileA = await seedFile(prisma, projectId, rootFolderId, `e2e-mvsh-a-${Date.now()}`)
|
||||
const fileB = await seedFile(prisma, projectId, rootFolderId, `e2e-mvsh-b-${Date.now()}`)
|
||||
const fileC = await seedFile(prisma, projectId, rootFolderId, `e2e-mvsh-c-${Date.now()}`)
|
||||
|
||||
await page.goto(`/projects/${projectId}`)
|
||||
|
||||
// 1. Create a version stack from file B and file A (stack has v2, displays file B)
|
||||
await dragCard(page, fileCard(page, fileB.name), fileCard(page, fileA.name))
|
||||
await expect(page.getByText('v2', { exact: true })).toBeVisible()
|
||||
|
||||
const stack = await prisma.asset.findFirstOrThrow({
|
||||
where: { projectId, parentId: rootFolderId, type: 'version_stack' },
|
||||
})
|
||||
|
||||
// 2. Create a share link and add both stack AB and file C to it
|
||||
const share = await apiCreateShare(project.context.request, projectId, `Test Share ${Date.now()}`)
|
||||
await apiAddAssetsToShare(project.context.request, share.id, [stack.id, fileC.id])
|
||||
|
||||
// Verify initial share page has both stack and file C
|
||||
await page.goto(`/share/${share.id}`)
|
||||
await expect(fileCard(page, fileB.name)).toBeVisible()
|
||||
await expect(fileCard(page, fileC.name)).toBeVisible()
|
||||
|
||||
// 3. In project page, drop file C onto stack card (displays file B)
|
||||
await page.goto(`/projects/${projectId}`)
|
||||
await dragCard(page, fileCard(page, fileC.name), fileCard(page, fileB.name))
|
||||
await expect(page.getByText('v3', { exact: true })).toBeVisible()
|
||||
|
||||
// 4. Return to public share page: now only 1 card exists (the stack showing file C with v3)
|
||||
await page.goto(`/share/${share.id}`)
|
||||
await expect(page.getByText('v3', { exact: true })).toBeVisible()
|
||||
await expect(fileCard(page, fileC.name)).toBeVisible()
|
||||
await expect(fileCard(page, fileB.name)).not.toBeVisible()
|
||||
|
||||
// DB: share rootFolder fileCount is 1 and exactly 1 symlink exists
|
||||
const symlinks = await prisma.asset.findMany({
|
||||
where: { parentId: share.rootFolderId, type: 'symlink' },
|
||||
})
|
||||
expect(symlinks).toHaveLength(1)
|
||||
expect(symlinks[0].targetId).toBe(stack.id)
|
||||
|
||||
const updatedShareRoot = await prisma.asset.findUnique({ where: { id: share.rootFolderId } })
|
||||
expect(updatedShareRoot?.fileCount).toBe(1)
|
||||
})
|
||||
@@ -0,0 +1,121 @@
|
||||
import { expect, test } from '../../fixtures'
|
||||
|
||||
test('owner manages resource quotas in settings and resets usage from the dashboard', async ({
|
||||
owner,
|
||||
prisma,
|
||||
}) => {
|
||||
const { page, teamId, email } = owner
|
||||
|
||||
// 1. Navigate to team settings
|
||||
await page.goto(`/teams/${teamId}/settings`)
|
||||
|
||||
// 2. Click the Quotas sidebar tab
|
||||
await page.getByRole('button', { name: /Quotas|配额/i }).click()
|
||||
|
||||
// 3. Verify Quotas settings card is displayed with empty state
|
||||
await expect(page.getByRole('heading', { name: /^(Resource Quotas|资源配额)$/i })).toBeVisible()
|
||||
await expect(page.getByText(/No resource quotas configured|暂未配置资源配额/i)).toBeVisible()
|
||||
|
||||
// 4. Open Create Quota Dialog
|
||||
await page
|
||||
.getByRole('button', { name: /Add Quota|添加配额/i })
|
||||
.first()
|
||||
.click()
|
||||
await expect(page.getByText(/Create Quota Rule|创建配额规则/i)).toBeVisible()
|
||||
|
||||
// 5. Fill and submit new quota rule
|
||||
await page.fill('#quota-limit', '50000')
|
||||
await page.getByRole('button', { name: /^(Create|创建)$/i }).click()
|
||||
|
||||
// 6. Verify quota rule card appears in the list
|
||||
await expect(page.getByText(/50,000 tokens|50000 tokens/i)).toBeVisible()
|
||||
await expect(page.getByText(/Each Member|每个成员/i)).toBeVisible()
|
||||
|
||||
// Verify in database
|
||||
const createdRule = await prisma.quotaRule.findFirst({
|
||||
where: { teamId, limit: 50000 },
|
||||
})
|
||||
expect(createdRule).not.toBeNull()
|
||||
expect(createdRule?.enabled).toBe(true)
|
||||
|
||||
// 7. Usage is now monitored from the dashboard, not the settings rule card.
|
||||
await expect(page.getByRole('button', { name: /View Usage|查看使用量/i })).not.toBeVisible()
|
||||
|
||||
// 8. Toggle quota rule switch
|
||||
await page.getByRole('switch').click()
|
||||
await expect(page.getByRole('switch')).not.toBeChecked()
|
||||
const disabledRule = await prisma.quotaRule.findFirst({
|
||||
where: { id: createdRule?.id },
|
||||
})
|
||||
expect(disabledRule?.enabled).toBe(false)
|
||||
|
||||
// Toggle back on
|
||||
await page.getByRole('switch').click()
|
||||
await expect(page.getByRole('switch')).toBeChecked()
|
||||
|
||||
// 9. Open Edit Dialog by clicking the quota card
|
||||
await page.getByText(/50,000 tokens|50000 tokens/i).click()
|
||||
await expect(page.getByText(/Edit Quota Rule|编辑配额规则/i)).toBeVisible()
|
||||
await expect(page.getByRole('button', { name: /Each Member|每个成员/i })).toBeDisabled()
|
||||
await expect(page.locator('#quota-resource')).toBeDisabled()
|
||||
|
||||
// 10. Update limit
|
||||
await page.fill('#quota-limit', '75000')
|
||||
await page.getByRole('button', { name: /^(Save|保存)$/i }).click()
|
||||
|
||||
// Verify updated limit in UI and DB
|
||||
await expect(page.getByText(/75,000 tokens|75000 tokens/i)).toBeVisible()
|
||||
const updatedRule = await prisma.quotaRule.findFirst({
|
||||
where: { id: createdRule?.id },
|
||||
})
|
||||
expect(updatedRule?.limit).toBe(75000)
|
||||
|
||||
// 11. Verify quota usage and reset it from the dashboard
|
||||
const ownerUser = await prisma.user.findUnique({ where: { email } })
|
||||
expect(ownerUser).not.toBeNull()
|
||||
await prisma.quotaRecord.create({
|
||||
data: {
|
||||
ruleId: createdRule?.id as string,
|
||||
teamId,
|
||||
userId: ownerUser?.id,
|
||||
periodStart: new Date(),
|
||||
periodEnd: new Date(Date.now() + 24 * 60 * 60 * 1000),
|
||||
consumed: 100,
|
||||
},
|
||||
})
|
||||
await page.goto(`/teams/${teamId}/dashboard`)
|
||||
await page.getByRole('button', { name: /Quotas|配额/i }).click()
|
||||
await expect(
|
||||
page.getByText(/Monitor live quota usage|在仪表盘中监控实时配额使用情况/),
|
||||
).toBeVisible()
|
||||
|
||||
const quotaRuleButton = page.getByRole('button', { name: /Expand quota rule|展开配额规则/i })
|
||||
await quotaRuleButton.click()
|
||||
await expect(page.getByText(/^100 \/ 75,000 tokens$|^100 \/ 75000 tokens$/i)).toBeVisible()
|
||||
await page.getByRole('button', { name: /Reset Usage|重置使用量/i }).click()
|
||||
await expect(page.getByRole('alertdialog')).toBeVisible()
|
||||
await page.getByRole('button', { name: /Confirm|确认/i }).click()
|
||||
await expect(page.getByText(/^0 \/ 75,000 tokens$|^0 \/ 75000 tokens$/i)).toBeVisible()
|
||||
|
||||
const resetRecord = await prisma.quotaRecord.findFirst({
|
||||
where: { ruleId: createdRule?.id, userId: ownerUser?.id },
|
||||
})
|
||||
expect(resetRecord?.consumed).toBe(0)
|
||||
|
||||
// 12. Delete quota rule from settings
|
||||
await page.goto(`/teams/${teamId}/settings`)
|
||||
await page.getByRole('button', { name: /Quotas|配额/i }).click()
|
||||
await page.getByRole('button', { name: 'Quota actions' }).first().click()
|
||||
await page.getByRole('menuitem', { name: /Delete|删除/i }).click()
|
||||
await page
|
||||
.getByRole('button', { name: /Delete|删除/i })
|
||||
.last()
|
||||
.click()
|
||||
|
||||
// Verify empty state returns
|
||||
await expect(page.getByText(/No resource quotas configured|暂未配置资源配额/i)).toBeVisible()
|
||||
const deletedRule = await prisma.quotaRule.findFirst({
|
||||
where: { id: createdRule?.id },
|
||||
})
|
||||
expect(deletedRule).toBeNull()
|
||||
})
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/web-app",
|
||||
"version": "0.3.7",
|
||||
"version": "0.4.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
|
||||
@@ -13,12 +13,37 @@ import { initTranscodeWorkflows } from '@shumai/transcode'
|
||||
import { workflowService } from '@shumai/workflow-core'
|
||||
|
||||
import { handleDaemonCommands } from '@shumai/core/src/utils/daemon'
|
||||
import { authService } from '@shumai/core/src/auth/auth'
|
||||
|
||||
if (process.argv.includes('--check')) {
|
||||
console.log('✅ Web app evaluated successfully!')
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
const cliArgs = process.argv.slice(2)
|
||||
const resetCmdIndex = cliArgs.findIndex(
|
||||
(arg) => arg === 'reset-password' || arg === 'reset-passowrd',
|
||||
)
|
||||
|
||||
if (resetCmdIndex !== -1) {
|
||||
const email = cliArgs[resetCmdIndex + 1]
|
||||
if (!email || email.startsWith('-')) {
|
||||
console.error('Error: Please provide a valid email address.')
|
||||
console.error('Usage: shumai reset-password <email>')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
try {
|
||||
const link = await authService.generatePasswordResetLink(email)
|
||||
console.log(link)
|
||||
process.exit(0)
|
||||
} catch (err: unknown) {
|
||||
const message = err instanceof Error ? err.message : 'Unknown error'
|
||||
console.error(`Error: ${message}`)
|
||||
process.exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
async function run() {
|
||||
// Initialize workflows and activities for local executor mode
|
||||
initAgentWorkflows()
|
||||
|
||||
@@ -33,7 +33,7 @@
|
||||
},
|
||||
"apps/agent": {
|
||||
"name": "@shumai/agent-app",
|
||||
"version": "0.3.6",
|
||||
"version": "0.3.7",
|
||||
"bin": {
|
||||
"shumai-agent": "./src/index.ts",
|
||||
},
|
||||
@@ -45,7 +45,7 @@
|
||||
},
|
||||
"apps/cli": {
|
||||
"name": "@shumai/cli",
|
||||
"version": "0.3.6",
|
||||
"version": "0.3.7",
|
||||
"bin": {
|
||||
"shumai-cli": "./src/index.ts",
|
||||
},
|
||||
@@ -60,7 +60,7 @@
|
||||
},
|
||||
"apps/transcode": {
|
||||
"name": "@shumai/transcode-app",
|
||||
"version": "0.3.6",
|
||||
"version": "0.3.7",
|
||||
"bin": {
|
||||
"shumai-transcode": "./src/index.ts",
|
||||
},
|
||||
@@ -72,7 +72,7 @@
|
||||
},
|
||||
"apps/web": {
|
||||
"name": "@shumai/web-app",
|
||||
"version": "0.3.6",
|
||||
"version": "0.3.7",
|
||||
"dependencies": {
|
||||
"@shumai/agent": "workspace:*",
|
||||
"@shumai/api": "workspace:*",
|
||||
@@ -92,7 +92,7 @@
|
||||
},
|
||||
"packages/agent": {
|
||||
"name": "@shumai/agent",
|
||||
"version": "0.3.6",
|
||||
"version": "0.3.7",
|
||||
"dependencies": {
|
||||
"@anthropic-ai/sandbox-runtime": "0.0.66",
|
||||
"@earendil-works/pi-agent-core": "0.82.1",
|
||||
@@ -117,7 +117,7 @@
|
||||
},
|
||||
"packages/api": {
|
||||
"name": "@shumai/api",
|
||||
"version": "0.3.6",
|
||||
"version": "0.3.7",
|
||||
"dependencies": {
|
||||
"@hono/zod-validator": "0.7.6",
|
||||
"@shumai/core": "workspace:*",
|
||||
@@ -131,7 +131,7 @@
|
||||
},
|
||||
"packages/core": {
|
||||
"name": "@shumai/core",
|
||||
"version": "0.3.6",
|
||||
"version": "0.3.7",
|
||||
"dependencies": {
|
||||
"@earendil-works/pi-agent-core": "0.82.1",
|
||||
"@earendil-works/pi-ai": "0.82.1",
|
||||
@@ -166,7 +166,7 @@
|
||||
},
|
||||
"packages/db": {
|
||||
"name": "@shumai/db",
|
||||
"version": "0.3.6",
|
||||
"version": "0.3.7",
|
||||
"dependencies": {
|
||||
"@earendil-works/pi-agent-core": "0.82.1",
|
||||
"@prisma/adapter-pg": "7.8.0",
|
||||
@@ -182,7 +182,7 @@
|
||||
},
|
||||
"packages/dtos": {
|
||||
"name": "@shumai/dtos",
|
||||
"version": "0.3.6",
|
||||
"version": "0.3.7",
|
||||
"dependencies": {
|
||||
"@earendil-works/pi-agent-core": "0.82.1",
|
||||
"zod": "4.4.3",
|
||||
@@ -190,7 +190,7 @@
|
||||
},
|
||||
"packages/e2e": {
|
||||
"name": "@shumai/e2e",
|
||||
"version": "0.3.6",
|
||||
"version": "0.3.7",
|
||||
"dependencies": {
|
||||
"@earendil-works/pi-agent-core": "0.82.1",
|
||||
"@google/genai": "1.52.0",
|
||||
@@ -205,11 +205,11 @@
|
||||
},
|
||||
"packages/tableprinter": {
|
||||
"name": "@shumai/tableprinter",
|
||||
"version": "0.3.6",
|
||||
"version": "0.3.7",
|
||||
},
|
||||
"packages/transcode": {
|
||||
"name": "@shumai/transcode",
|
||||
"version": "0.3.6",
|
||||
"version": "0.3.7",
|
||||
"dependencies": {
|
||||
"@shumai/core": "workspace:*",
|
||||
"@shumai/db": "workspace:*",
|
||||
@@ -223,7 +223,7 @@
|
||||
},
|
||||
"packages/webui": {
|
||||
"name": "@shumai/webui",
|
||||
"version": "0.3.6",
|
||||
"version": "0.3.7",
|
||||
"dependencies": {
|
||||
"@base-ui/react": "1.5.0",
|
||||
"@dnd-kit/abstract": "0.4.0",
|
||||
@@ -321,7 +321,7 @@
|
||||
},
|
||||
"packages/workflow-core": {
|
||||
"name": "@shumai/workflow-core",
|
||||
"version": "0.3.6",
|
||||
"version": "0.3.7",
|
||||
"dependencies": {
|
||||
"@shumai/core": "workspace:*",
|
||||
"@shumai/db": "workspace:*",
|
||||
|
||||
+7
-2
@@ -43,6 +43,7 @@
|
||||
"pages": [
|
||||
"using-shumai/agent-providers",
|
||||
"using-shumai/agents",
|
||||
"using-shumai/agents-md",
|
||||
"using-shumai/agent-skills",
|
||||
"using-shumai/agent-tools",
|
||||
"using-shumai/mcp-servers",
|
||||
@@ -50,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,53 @@
|
||||
---
|
||||
title: AGENTS.md Context & Instructions
|
||||
description: Provide hierarchical, folder-specific instructions and context to AI agents.
|
||||
---
|
||||
|
||||
In addition to global agent system prompts and skills, Shumai allows you to define project-level and folder-level instructions using **`AGENTS.md`**.
|
||||
|
||||
When an AI agent (such as a Chat Agent or Autofill Agent) operates within a project or folder, Shumai automatically loads the corresponding `AGENTS.md` files to provide context, operational rules, and project-specific knowledge.
|
||||
|
||||
---
|
||||
|
||||
## Hierarchical Traversal & Inheritance
|
||||
|
||||
Shumai uses a hierarchical context model for `AGENTS.md`:
|
||||
|
||||
- **Upward Traversal**: When an agent works on a file or folder, Shumai traverses the folder tree upwards from the current folder all the way to the **project root level**.
|
||||
- **Combined Context**: All `AGENTS.md` files found along this path are loaded into the agent's context in order (from the project root down to the current folder).
|
||||
- **Layered Rules**: This lets you define broad, project-wide rules and guidelines at the project root `AGENTS.md`, while adding specific rules, vocabulary, or autofill hints in nested subfolder `AGENTS.md` files.
|
||||
|
||||
---
|
||||
|
||||
## What to Include in AGENTS.md
|
||||
|
||||
You can use `AGENTS.md` to define any instructions you want the agent to follow when working in that folder or project:
|
||||
|
||||
- **Project & Folder Overview**: Describe what assets are stored in the folder and how they relate to the broader project.
|
||||
- **Agent Behavioral Rules**: Specify guardrails, tone, required formats, or things the agent should and shouldn't do when answering queries or leaving comments.
|
||||
- **Terminology & Domain Knowledge**: Define specialized vocabulary, acronyms, brand naming conventions, or project-specific jargon.
|
||||
- **Metadata & Autofill Instructions**: Guide the **Autofill Agent** on how to summarize assets, generate tags, or populate specific custom metadata fields for files in this folder.
|
||||
|
||||
---
|
||||
|
||||
## Accessing and Editing AGENTS.md
|
||||
|
||||
### Opening the Editor
|
||||
|
||||
To view or edit `AGENTS.md`:
|
||||
|
||||
1. Open any project or folder in the Shumai web application.
|
||||
2. Click the **`AGENTS.md`** button in the top navigation toolbar, or right-click any folder in the file browser and choose **AGENTS.md**.
|
||||
3. A dedicated WYSIWYG Markdown editor opens with full formatting support (headings, lists, code blocks, bold/italics, and links).
|
||||
|
||||
### Auto-Save
|
||||
|
||||
As you make changes in the editor, Shumai automatically saves your edits in the background with visual save status indicators (`Saving...`, `Saved`).
|
||||
|
||||
---
|
||||
|
||||
## Permissions & Read-Only Mode
|
||||
|
||||
- **Viewing**: All team members who have read access to the project can view `AGENTS.md`.
|
||||
- **Editing**: **Only Team Owners** are permitted to create, edit, or delete `AGENTS.md` files.
|
||||
- **Read-Only State**: Non-owner members will see a clear read-only indicator in the toolbar explaining that only team owners can edit instructions for the file.
|
||||
@@ -0,0 +1,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.7",
|
||||
"version": "0.4.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"repository": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/agent",
|
||||
"version": "0.3.7",
|
||||
"version": "0.4.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -13,11 +13,12 @@ import {
|
||||
getCommentActivity,
|
||||
getProjectAutofillFieldsActivity,
|
||||
updateAssetMetadataActivity,
|
||||
getAssetPathHierarchyActivity,
|
||||
getAssetPathContextActivity,
|
||||
executeAgentToolActivity,
|
||||
generateSessionNameActivity,
|
||||
type GenerateSessionNameParams,
|
||||
getUserTeamInfoActivity,
|
||||
formatProjectContextPrompt,
|
||||
} from './agent'
|
||||
import * as piAgent from '../index'
|
||||
import { type AgentHarness, type Session } from '@earendil-works/pi-agent-core'
|
||||
@@ -35,8 +36,6 @@ import {
|
||||
type Asset,
|
||||
} from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { authzService } from '@shumai/core/src/authz/authz'
|
||||
import { uploadService } from '@shumai/core/src/upload/upload'
|
||||
|
||||
vi.mock('../index', async () => {
|
||||
const actual = await vi.importActual('../index')
|
||||
@@ -513,6 +512,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
|
||||
@@ -561,8 +565,18 @@ describe('Agent Database Activities Integration', () => {
|
||||
|
||||
describe('initializeAgentSessionActivity', () => {
|
||||
it('should initialize a session, create agent/user records if missing, and store existing comments context', async () => {
|
||||
const attAsset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'attached-doc.pdf',
|
||||
type: AssetType.file,
|
||||
mediaType: 'application/pdf',
|
||||
status: AssetStatus.uploaded,
|
||||
projectId: project.id,
|
||||
},
|
||||
})
|
||||
|
||||
// Create first comment so it acts as context
|
||||
await prisma.assetComment.create({
|
||||
const firstComment = await prisma.assetComment.create({
|
||||
data: {
|
||||
assetId: asset.id,
|
||||
message: 'Hello <@' + user.id + '> check this',
|
||||
@@ -570,6 +584,14 @@ describe('Agent Database Activities Integration', () => {
|
||||
},
|
||||
})
|
||||
|
||||
await prisma.assetCommentAttachment.create({
|
||||
data: {
|
||||
commentId: firstComment.id,
|
||||
assetId: attAsset.id,
|
||||
},
|
||||
})
|
||||
|
||||
await sleep(2)
|
||||
// Create second comment that user responds with, triggering session initialization
|
||||
const userComment = await prisma.assetComment.create({
|
||||
data: {
|
||||
@@ -607,9 +629,20 @@ describe('Agent Database Activities Integration', () => {
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- entry data is stored as Json in DB and needs casting to check properties
|
||||
const parsedEntry = pathEntries[0] as any
|
||||
expect(parsedEntry.message.content[0].text).toContain(
|
||||
`[${user.name} (owner)]: Hello <@${user.name}> check this`,
|
||||
)
|
||||
expect(parsedEntry.type).toBe('custom_message')
|
||||
expect(parsedEntry.customType).toBe('shumai_message')
|
||||
expect(parsedEntry.content).toContain(`Hello <@${user.name}> check this`)
|
||||
expect(parsedEntry.details.user.name).toBe(user.name)
|
||||
expect(parsedEntry.details.user.role).toBe('owner')
|
||||
expect(parsedEntry.details.attachedFiles).toEqual([
|
||||
{
|
||||
id: attAsset.id,
|
||||
name: 'attached-doc.pdf',
|
||||
type: 'file',
|
||||
mediaType: undefined,
|
||||
mimeType: 'application/pdf',
|
||||
},
|
||||
])
|
||||
})
|
||||
|
||||
it('should distinguish Main Session (userCommentId: null) and Thread Session (userCommentId: rootId) during lazy sync', async () => {
|
||||
@@ -617,11 +650,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,
|
||||
@@ -721,7 +756,7 @@ describe('Agent Database Activities Integration', () => {
|
||||
const msg3Entry = pathEntries.find((e) => e.id.includes(msg3.id))
|
||||
expect(msg3Entry).toBeDefined()
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const text = (msg3Entry as any).message.content[0].text
|
||||
const text = (msg3Entry as any).content ?? (msg3Entry as any).message?.content[0]?.text
|
||||
expect(text).toContain(`[Thread ID: ${msg3.id}] [Replies: 1]`)
|
||||
})
|
||||
|
||||
@@ -730,10 +765,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 },
|
||||
@@ -748,6 +785,7 @@ describe('Agent Database Activities Integration', () => {
|
||||
})
|
||||
|
||||
// agent response msg4
|
||||
await sleep(2)
|
||||
const msg4 = await prisma.assetComment.create({
|
||||
data: {
|
||||
assetId: asset.id,
|
||||
@@ -759,6 +797,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 },
|
||||
})
|
||||
@@ -782,6 +821,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,
|
||||
@@ -830,10 +870,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 },
|
||||
@@ -868,10 +910,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 },
|
||||
@@ -1085,6 +1129,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: {
|
||||
@@ -1276,10 +1369,14 @@ describe('Agent Database Activities Integration', () => {
|
||||
})
|
||||
|
||||
const pathCtx = await getAssetPathContextActivity(targetAsset.id)
|
||||
expect(pathCtx).toContain('Path: RootFolder/SubFolder/TargetImage.webp')
|
||||
expect(pathCtx).toContain(`name: RootFolder, id: ${rootFolder.id}`)
|
||||
expect(pathCtx).toContain(`name: SubFolder, id: ${subfolder.id}`)
|
||||
expect(pathCtx).toContain(`name: TargetImage.webp, id: ${targetAsset.id}`)
|
||||
expect(pathCtx).toBe('RootFolder/SubFolder/TargetImage.webp')
|
||||
|
||||
const hierarchy = await getAssetPathHierarchyActivity(targetAsset.id)
|
||||
expect(hierarchy.path).toBe('RootFolder/SubFolder/TargetImage.webp')
|
||||
expect(hierarchy.ancestors).toEqual([
|
||||
{ id: rootFolder.id, name: 'RootFolder' },
|
||||
{ id: subfolder.id, name: 'SubFolder' },
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1311,556 +1408,6 @@ describe('Agent Database Activities Integration', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('executeAgentToolActivity', () => {
|
||||
beforeEach(() => {
|
||||
vi.spyOn(authzService, 'hasPermission').mockResolvedValue()
|
||||
vi.spyOn(uploadService, 'triggerPostUploadWorkflows').mockResolvedValue()
|
||||
})
|
||||
|
||||
describe('list_assets', () => {
|
||||
it('should list assets inside a folder with cursor pagination', async () => {
|
||||
const folder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'WorkspaceFolder',
|
||||
type: AssetType.folder,
|
||||
status: AssetStatus.uploaded,
|
||||
projectId: project.id,
|
||||
},
|
||||
})
|
||||
|
||||
await prisma.asset.create({
|
||||
data: {
|
||||
name: 'file1.txt',
|
||||
type: AssetType.file,
|
||||
status: AssetStatus.uploaded,
|
||||
projectId: project.id,
|
||||
parentId: folder.id,
|
||||
},
|
||||
})
|
||||
|
||||
await prisma.asset.create({
|
||||
data: {
|
||||
name: 'subfolder1',
|
||||
type: AssetType.folder,
|
||||
status: AssetStatus.uploaded,
|
||||
projectId: project.id,
|
||||
parentId: folder.id,
|
||||
},
|
||||
})
|
||||
|
||||
const res = await executeAgentToolActivity({
|
||||
taskId: 'task-1',
|
||||
toolName: 'list_assets',
|
||||
args: { parent: folder.id, page: 1, pageSize: 1 },
|
||||
userId: user.id,
|
||||
})
|
||||
|
||||
expect(res.assets.length).toBe(1)
|
||||
expect(res.pageInfo.cursor).toBeDefined()
|
||||
})
|
||||
|
||||
it('should resolve version_stack name and size from top child version when container name is empty', async () => {
|
||||
const folder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'WorkspaceFolder',
|
||||
type: AssetType.folder,
|
||||
status: AssetStatus.uploaded,
|
||||
projectId: project.id,
|
||||
},
|
||||
})
|
||||
|
||||
const versionStack = await prisma.asset.create({
|
||||
data: {
|
||||
name: '',
|
||||
type: AssetType.version_stack,
|
||||
status: AssetStatus.uploaded,
|
||||
projectId: project.id,
|
||||
parentId: folder.id,
|
||||
},
|
||||
})
|
||||
|
||||
await prisma.asset.create({
|
||||
data: {
|
||||
name: 'banana_ghost.txt',
|
||||
type: AssetType.file,
|
||||
status: AssetStatus.uploaded,
|
||||
projectId: project.id,
|
||||
parentId: versionStack.id,
|
||||
sizeByte: 622960,
|
||||
sortIndex: '0|i00000:',
|
||||
},
|
||||
})
|
||||
|
||||
const res = await executeAgentToolActivity({
|
||||
taskId: 'task-1',
|
||||
toolName: 'list_assets',
|
||||
args: { parent: folder.id, page: 1, pageSize: 10 },
|
||||
userId: user.id,
|
||||
})
|
||||
|
||||
const stackItem = res.assets.find(
|
||||
(a: { id: string; name: string; size: number; type: string }) => a.id === versionStack.id,
|
||||
)
|
||||
expect(stackItem).toBeDefined()
|
||||
expect(stackItem?.name).toBe('banana_ghost.txt')
|
||||
expect(stackItem?.size).toBe(622960)
|
||||
expect(stackItem?.type).toBe('version_stack')
|
||||
})
|
||||
})
|
||||
|
||||
describe('create_folder', () => {
|
||||
it('should create folder and increment parent fileCount', async () => {
|
||||
const folder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'WorkspaceFolder',
|
||||
type: AssetType.folder,
|
||||
status: AssetStatus.uploaded,
|
||||
projectId: project.id,
|
||||
fileCount: 0,
|
||||
},
|
||||
})
|
||||
|
||||
const res = await executeAgentToolActivity({
|
||||
taskId: 'task-1',
|
||||
toolName: 'create_folder',
|
||||
args: { parent: folder.id, name: 'subfolder' },
|
||||
userId: user.id,
|
||||
})
|
||||
|
||||
expect(res.name).toBe('subfolder')
|
||||
expect(res.type).toBe('folder')
|
||||
|
||||
const parentFolder = await prisma.asset.findUnique({ where: { id: folder.id } })
|
||||
expect(parentFolder?.fileCount).toBe(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('create_file', () => {
|
||||
it('should create file, increment parent fileCount, and update parent sizes', async () => {
|
||||
const folder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'WorkspaceFolder',
|
||||
type: AssetType.folder,
|
||||
status: AssetStatus.uploaded,
|
||||
projectId: project.id,
|
||||
fileCount: 0,
|
||||
sizeByte: 0,
|
||||
},
|
||||
})
|
||||
|
||||
const res = await executeAgentToolActivity({
|
||||
taskId: 'task-1',
|
||||
toolName: 'create_file',
|
||||
args: {
|
||||
parent: folder.id,
|
||||
s3Key: 'uploads/testfile.txt',
|
||||
name: 'testfile.txt',
|
||||
size: 500,
|
||||
contentType: 'text/plain',
|
||||
},
|
||||
userId: user.id,
|
||||
})
|
||||
|
||||
expect(res.name).toBe('testfile.txt')
|
||||
expect(res.size).toBe(500)
|
||||
|
||||
const parentFolder = await prisma.asset.findUnique({ where: { id: folder.id } })
|
||||
expect(parentFolder?.fileCount).toBe(1)
|
||||
expect(Number(parentFolder?.sizeByte)).toBe(500)
|
||||
expect(uploadService.triggerPostUploadWorkflows).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should persist metadata on the created file when metadata map is provided', async () => {
|
||||
await prisma.metadataField.create({
|
||||
data: {
|
||||
key: 'prompt',
|
||||
scope: 'PROJECT',
|
||||
projectId: project.id,
|
||||
teamId: team.id,
|
||||
config: { name: 'Prompt', type: 'text', autofillSource: 'CREATION_CONTEXT' },
|
||||
},
|
||||
})
|
||||
|
||||
const folder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'WorkspaceFolder',
|
||||
type: AssetType.folder,
|
||||
status: AssetStatus.uploaded,
|
||||
projectId: project.id,
|
||||
fileCount: 0,
|
||||
sizeByte: 0,
|
||||
},
|
||||
})
|
||||
|
||||
const res = await executeAgentToolActivity({
|
||||
taskId: 'task-1',
|
||||
toolName: 'create_file',
|
||||
args: {
|
||||
parent: folder.id,
|
||||
s3Key: 'uploads/ctx.txt',
|
||||
name: 'ctx.txt',
|
||||
size: 100,
|
||||
contentType: 'text/plain',
|
||||
metadata: { prompt: 'Generated using gemini' },
|
||||
},
|
||||
userId: user.id,
|
||||
})
|
||||
|
||||
const val = await prisma.assetMetadataValue.findFirst({
|
||||
where: { assetId: res.id, fieldKey: 'prompt' },
|
||||
})
|
||||
expect(val?.stringValue).toBe('Generated using gemini')
|
||||
})
|
||||
|
||||
it('should persist select and selectMulti metadata with dynamic newOption', async () => {
|
||||
const selectField = await prisma.metadataField.create({
|
||||
data: {
|
||||
key: 'provider',
|
||||
scope: 'PROJECT',
|
||||
project: { connect: { id: project.id } },
|
||||
config: {
|
||||
name: 'Provider',
|
||||
type: 'select',
|
||||
autofillSource: 'CREATION_CONTEXT',
|
||||
select: { options: [{ id: 'openai', displayName: 'OpenAI', color: '#f43f5e' }] },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const multiField = await prisma.metadataField.create({
|
||||
data: {
|
||||
key: 'tags',
|
||||
scope: 'PROJECT',
|
||||
project: { connect: { id: project.id } },
|
||||
config: {
|
||||
name: 'Tags',
|
||||
type: 'selectMulti',
|
||||
autofillSource: 'CREATION_CONTEXT',
|
||||
selectMulti: { options: [{ id: 'tag1', displayName: 'Tag 1', color: '#3b82f6' }] },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const folder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'WorkspaceFolder',
|
||||
type: AssetType.folder,
|
||||
status: AssetStatus.uploaded,
|
||||
projectId: project.id,
|
||||
fileCount: 0,
|
||||
sizeByte: 0,
|
||||
},
|
||||
})
|
||||
|
||||
const res = await executeAgentToolActivity({
|
||||
taskId: 'task-1',
|
||||
toolName: 'create_file',
|
||||
args: {
|
||||
parent: folder.id,
|
||||
s3Key: 'uploads/new_opt.txt',
|
||||
name: 'new_opt.txt',
|
||||
size: 100,
|
||||
contentType: 'text/plain',
|
||||
metadata: {
|
||||
provider: { newOption: { value: 'Kling' } },
|
||||
tags: ['tag1', { newOption: { value: 'Tag 2' } }],
|
||||
},
|
||||
},
|
||||
userId: user.id,
|
||||
})
|
||||
|
||||
// Verify select field
|
||||
const providerVal = await prisma.assetMetadataValue.findFirst({
|
||||
where: { assetId: res.id, fieldKey: selectField.key },
|
||||
})
|
||||
expect(providerVal?.stringValue).toBe('kling')
|
||||
|
||||
// Verify select field config was updated with new option
|
||||
const updatedSelectField = await prisma.metadataField.findUnique({
|
||||
where: { key: selectField.key },
|
||||
})
|
||||
const selectOpts =
|
||||
(updatedSelectField?.config as PrismaJson.FieldConfig)?.select?.options || []
|
||||
expect(selectOpts.some((o) => o.displayName === 'Kling' && o.id === 'kling')).toBe(true)
|
||||
|
||||
// Verify selectMulti field
|
||||
const tagsVal = await prisma.assetMetadataValue.findFirst({
|
||||
where: { assetId: res.id, fieldKey: multiField.key },
|
||||
})
|
||||
expect(tagsVal?.jsonValue).toEqual(['tag1', 'tag-2'])
|
||||
|
||||
// Verify selectMulti field config was updated with new option
|
||||
const updatedMultiField = await prisma.metadataField.findUnique({
|
||||
where: { key: multiField.key },
|
||||
})
|
||||
const multiOpts =
|
||||
(updatedMultiField?.config as PrismaJson.FieldConfig)?.selectMulti?.options || []
|
||||
expect(multiOpts.some((o) => o.displayName === 'Tag 2' && o.id === 'tag-2')).toBe(true)
|
||||
})
|
||||
|
||||
it('should reject metadata with keys that are not valid in this project', async () => {
|
||||
const folder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'WorkspaceFolder',
|
||||
type: AssetType.folder,
|
||||
status: AssetStatus.uploaded,
|
||||
projectId: project.id,
|
||||
fileCount: 0,
|
||||
sizeByte: 0,
|
||||
},
|
||||
})
|
||||
|
||||
await expect(
|
||||
executeAgentToolActivity({
|
||||
taskId: 'task-1',
|
||||
toolName: 'create_file',
|
||||
args: {
|
||||
parent: folder.id,
|
||||
s3Key: 'uploads/ctx.txt',
|
||||
name: 'ctx.txt',
|
||||
size: 100,
|
||||
contentType: 'text/plain',
|
||||
metadata: { prompt: 'ok', unknownKey: 'not allowed' },
|
||||
},
|
||||
userId: user.id,
|
||||
}),
|
||||
).rejects.toThrow(/not valid in this project/)
|
||||
|
||||
// No metadata value should have been written for the unknown key
|
||||
const val = await prisma.assetMetadataValue.findFirst({
|
||||
where: { fieldKey: 'unknownKey' },
|
||||
})
|
||||
expect(val).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('create_version', () => {
|
||||
it('should create a version stack when parent is a regular file', async () => {
|
||||
const folder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'WorkspaceFolder',
|
||||
type: AssetType.folder,
|
||||
status: AssetStatus.uploaded,
|
||||
projectId: project.id,
|
||||
fileCount: 1,
|
||||
sizeByte: 200,
|
||||
},
|
||||
})
|
||||
|
||||
const fileAsset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'v1.txt',
|
||||
type: AssetType.file,
|
||||
status: AssetStatus.uploaded,
|
||||
projectId: project.id,
|
||||
parentId: folder.id,
|
||||
sizeByte: 200,
|
||||
},
|
||||
})
|
||||
|
||||
const res = await executeAgentToolActivity({
|
||||
taskId: 'task-1',
|
||||
toolName: 'create_version',
|
||||
args: {
|
||||
parent: fileAsset.id,
|
||||
s3Key: 'uploads/v2.txt',
|
||||
name: 'v2.txt',
|
||||
size: 300,
|
||||
contentType: 'text/plain',
|
||||
},
|
||||
userId: user.id,
|
||||
})
|
||||
|
||||
expect(res.name).toBe('v2.txt')
|
||||
expect(res.size).toBe(300)
|
||||
|
||||
// Check version stack was created
|
||||
const stack = await prisma.asset.findFirst({
|
||||
where: { type: AssetType.version_stack, projectId: project.id },
|
||||
include: { children: true },
|
||||
})
|
||||
|
||||
expect(stack).not.toBeNull()
|
||||
expect(stack?.children.length).toBe(2) // v1.txt and v2.txt should both be inside the stack
|
||||
})
|
||||
|
||||
it('should add to version stack when parent is already inside a version stack', async () => {
|
||||
const folder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'WorkspaceFolder',
|
||||
type: AssetType.folder,
|
||||
status: AssetStatus.uploaded,
|
||||
projectId: project.id,
|
||||
},
|
||||
})
|
||||
|
||||
const stack = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'VersionStack',
|
||||
type: AssetType.version_stack,
|
||||
status: AssetStatus.uploaded,
|
||||
projectId: project.id,
|
||||
parentId: folder.id,
|
||||
fileCount: 1,
|
||||
sizeByte: 100,
|
||||
},
|
||||
})
|
||||
|
||||
const existingFileVersion = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'v1.txt',
|
||||
type: AssetType.file,
|
||||
status: AssetStatus.uploaded,
|
||||
projectId: project.id,
|
||||
parentId: stack.id,
|
||||
sizeByte: 100,
|
||||
},
|
||||
})
|
||||
|
||||
const res = await executeAgentToolActivity({
|
||||
taskId: 'task-1',
|
||||
toolName: 'create_version',
|
||||
args: {
|
||||
parent: existingFileVersion.id,
|
||||
s3Key: 'uploads/v2.txt',
|
||||
name: 'v2.txt',
|
||||
size: 250,
|
||||
contentType: 'text/plain',
|
||||
},
|
||||
userId: user.id,
|
||||
})
|
||||
|
||||
expect(res.name).toBe('v2.txt')
|
||||
|
||||
const updatedStack = await prisma.asset.findUnique({
|
||||
where: { id: stack.id },
|
||||
include: { children: true },
|
||||
})
|
||||
|
||||
expect(updatedStack?.fileCount).toBe(2)
|
||||
expect(Number(updatedStack?.sizeByte)).toBe(350)
|
||||
})
|
||||
|
||||
it('should persist metadata on the created version when metadata map is provided', async () => {
|
||||
await prisma.metadataField.create({
|
||||
data: {
|
||||
key: 'prompt',
|
||||
scope: 'PROJECT',
|
||||
projectId: project.id,
|
||||
teamId: team.id,
|
||||
config: { name: 'Prompt', type: 'text', autofillSource: 'CREATION_CONTEXT' },
|
||||
},
|
||||
})
|
||||
|
||||
const folder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'WorkspaceFolder',
|
||||
type: AssetType.folder,
|
||||
status: AssetStatus.uploaded,
|
||||
projectId: project.id,
|
||||
fileCount: 1,
|
||||
sizeByte: 200,
|
||||
},
|
||||
})
|
||||
|
||||
const fileAsset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'v1.txt',
|
||||
type: AssetType.file,
|
||||
status: AssetStatus.uploaded,
|
||||
projectId: project.id,
|
||||
parentId: folder.id,
|
||||
sizeByte: 200,
|
||||
},
|
||||
})
|
||||
|
||||
const res = await executeAgentToolActivity({
|
||||
taskId: 'task-1',
|
||||
toolName: 'create_version',
|
||||
args: {
|
||||
parent: fileAsset.id,
|
||||
s3Key: 'uploads/v2.txt',
|
||||
name: 'v2.txt',
|
||||
size: 300,
|
||||
contentType: 'text/plain',
|
||||
metadata: { prompt: 'Generated using seedance' },
|
||||
},
|
||||
userId: user.id,
|
||||
})
|
||||
|
||||
const val = await prisma.assetMetadataValue.findFirst({
|
||||
where: { assetId: res.id, fieldKey: 'prompt' },
|
||||
})
|
||||
expect(val?.stringValue).toBe('Generated using seedance')
|
||||
})
|
||||
|
||||
it('should persist select and selectMulti newOption metadata in create_version', async () => {
|
||||
const selectField = await prisma.metadataField.create({
|
||||
data: {
|
||||
key: 'versionProvider',
|
||||
scope: 'PROJECT',
|
||||
project: { connect: { id: project.id } },
|
||||
config: {
|
||||
name: 'Version Provider',
|
||||
type: 'select',
|
||||
autofillSource: 'CREATION_CONTEXT',
|
||||
select: { options: [{ id: 'openai', displayName: 'OpenAI', color: '#f43f5e' }] },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const folder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'WorkspaceFolder',
|
||||
type: AssetType.folder,
|
||||
status: AssetStatus.uploaded,
|
||||
projectId: project.id,
|
||||
fileCount: 1,
|
||||
sizeByte: 200,
|
||||
},
|
||||
})
|
||||
|
||||
const fileAsset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'v1.txt',
|
||||
type: AssetType.file,
|
||||
status: AssetStatus.uploaded,
|
||||
projectId: project.id,
|
||||
parentId: folder.id,
|
||||
sizeByte: 200,
|
||||
},
|
||||
})
|
||||
|
||||
const res = await executeAgentToolActivity({
|
||||
taskId: 'task-1',
|
||||
toolName: 'create_version',
|
||||
args: {
|
||||
parent: fileAsset.id,
|
||||
s3Key: 'uploads/v2.txt',
|
||||
name: 'v2.txt',
|
||||
size: 300,
|
||||
contentType: 'text/plain',
|
||||
metadata: {
|
||||
versionProvider: { newOption: { value: 'Midjourney' } },
|
||||
},
|
||||
},
|
||||
userId: user.id,
|
||||
})
|
||||
|
||||
const val = await prisma.assetMetadataValue.findFirst({
|
||||
where: { assetId: res.id, fieldKey: selectField.key },
|
||||
})
|
||||
expect(val?.stringValue).toBe('midjourney')
|
||||
|
||||
const updatedField = await prisma.metadataField.findUnique({
|
||||
where: { key: selectField.key },
|
||||
})
|
||||
const opts = (updatedField?.config as PrismaJson.FieldConfig)?.select?.options || []
|
||||
expect(opts.some((o) => o.displayName === 'Midjourney' && o.id === 'midjourney')).toBe(true)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('generateSessionNameActivity', () => {
|
||||
it('should generate and save session name for chat sessions', async () => {
|
||||
await prisma.team.create({
|
||||
@@ -2041,4 +1588,113 @@ describe('Agent Database Activities Integration', () => {
|
||||
expect(piAgent.createAgentSession).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('Nested AGENTS.md prompt injection', () => {
|
||||
it('formatProjectContextPrompt formats context files into XML project_context block', () => {
|
||||
expect(formatProjectContextPrompt([])).toBe('')
|
||||
|
||||
const formatted = formatProjectContextPrompt([
|
||||
{ path: '/AGENTS.md', content: 'Root rules' },
|
||||
{ path: '/subfolder/AGENTS.md', content: 'Subfolder rules' },
|
||||
])
|
||||
|
||||
expect(formatted).toBe(
|
||||
'\n\n<project_context>\n\nProject-specific instructions and guidelines:\n\n<project_instructions path="/AGENTS.md">\nRoot rules\n</project_instructions>\n\n<project_instructions path="/subfolder/AGENTS.md">\nSubfolder rules\n</project_instructions>\n\n</project_context>',
|
||||
)
|
||||
})
|
||||
|
||||
it('agentChatActivity injects nested AGENTS.md instructions into systemPrompt', async () => {
|
||||
const user = await prisma.user.create({
|
||||
data: { name: 'User_Chat_Md', email: `chat-md-${Date.now()}@example.com` },
|
||||
})
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'Team_Chat_Md_' + Date.now() },
|
||||
})
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'Project_Chat_Md', teamId: team.id },
|
||||
})
|
||||
const rootFolder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'Root',
|
||||
type: AssetType.root,
|
||||
projectId: project.id,
|
||||
status: AssetStatus.uploaded,
|
||||
},
|
||||
})
|
||||
await prisma.assetAgentMd.create({
|
||||
data: {
|
||||
assetId: rootFolder.id,
|
||||
content: '# Root Policy',
|
||||
},
|
||||
})
|
||||
const subfolder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'subfolder',
|
||||
type: AssetType.folder,
|
||||
parentId: rootFolder.id,
|
||||
projectId: project.id,
|
||||
status: AssetStatus.uploaded,
|
||||
},
|
||||
})
|
||||
await prisma.assetAgentMd.create({
|
||||
data: {
|
||||
assetId: subfolder.id,
|
||||
content: '# Subfolder Policy',
|
||||
},
|
||||
})
|
||||
|
||||
const mockHarness = {
|
||||
subscribe: vi.fn(),
|
||||
prompt: vi.fn().mockResolvedValue({
|
||||
content: [{ type: 'text', text: 'Chat reply' }],
|
||||
usage: { input: 10, output: 20 },
|
||||
}),
|
||||
}
|
||||
const mockSession = {
|
||||
getEntries: vi.fn().mockResolvedValue([]),
|
||||
getStorage: vi.fn().mockReturnValue({ sessionId: 'mock-session-id' }),
|
||||
}
|
||||
|
||||
vi.mocked(piAgent.createAgentSession).mockResolvedValue({
|
||||
session: mockSession as unknown as Session<DatabaseSessionMetadata>,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Mock AgentHarness instance for activity test
|
||||
harness: mockHarness as unknown as AgentHarness<any, any, any, any>,
|
||||
})
|
||||
|
||||
const context = {
|
||||
agent: { id: 'agent-1', provider: { name: 'google' }, modelRef: { modelId: 'gemini' } },
|
||||
dbProviders: [],
|
||||
teamSkills: [],
|
||||
allowedDomains: [],
|
||||
} as unknown as AgentExecutionContext
|
||||
|
||||
await agentChatActivity({
|
||||
teamId: team.id,
|
||||
agentId: 'agent-1',
|
||||
message: 'Hello',
|
||||
imageUrls: [],
|
||||
projectId: project.id,
|
||||
folderId: subfolder.id,
|
||||
assetId: subfolder.id,
|
||||
sessionId: 'mock-session-id',
|
||||
userId: user.id,
|
||||
context,
|
||||
})
|
||||
|
||||
expect(piAgent.createAgentSession).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
systemPrompt: expect.stringContaining('<project_context>'),
|
||||
}),
|
||||
)
|
||||
|
||||
const lastCall = vi.mocked(piAgent.createAgentSession).mock.calls.at(-1)
|
||||
const systemPromptArg = lastCall?.[0].systemPrompt as string
|
||||
expect(systemPromptArg).toContain(
|
||||
'<project_instructions path="/AGENTS.md">\n# Root Policy\n</project_instructions>',
|
||||
)
|
||||
expect(systemPromptArg).toContain(
|
||||
'<project_instructions path="/subfolder/AGENTS.md">\n# Subfolder Policy\n</project_instructions>',
|
||||
)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,315 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { escapeXmlAttr, serializeContextToXml } from './serialize-context'
|
||||
import type { ShumaiMessageContext } from '@shumai/dtos'
|
||||
|
||||
describe('serializeContextToXml', () => {
|
||||
describe('escapeXmlAttr', () => {
|
||||
it('escapes &, <, >, ", and \' characters correctly', () => {
|
||||
expect(escapeXmlAttr('Alice & Bob <Admin> "v1" \'test\'')).toBe(
|
||||
'Alice & Bob <Admin> "v1" 'test'',
|
||||
)
|
||||
})
|
||||
|
||||
it('handles clean strings without modification', () => {
|
||||
expect(escapeXmlAttr('normal-string_123.mp4')).toBe('normal-string_123.mp4')
|
||||
})
|
||||
})
|
||||
|
||||
describe('Tag Serialization', () => {
|
||||
it('returns empty string for null, undefined, or empty context', () => {
|
||||
expect(serializeContextToXml(null)).toBe('')
|
||||
expect(serializeContextToXml(undefined)).toBe('')
|
||||
expect(serializeContextToXml({})).toBe('')
|
||||
})
|
||||
|
||||
it('serializes minimal context with only user', () => {
|
||||
const context: ShumaiMessageContext = {
|
||||
user: { id: 'usr_1', name: 'Alice', role: 'editor' },
|
||||
}
|
||||
expect(serializeContextToXml(context)).toBe(
|
||||
'<context>\n <user id="usr_1" name="Alice" role="editor" />\n</context>',
|
||||
)
|
||||
})
|
||||
|
||||
it('serializes minimal context with only currentAsset (without ancestors)', () => {
|
||||
const context: ShumaiMessageContext = {
|
||||
currentAsset: {
|
||||
id: 'ast_1',
|
||||
name: 'clip.mp4',
|
||||
type: 'file',
|
||||
mediaType: 'video',
|
||||
path: 'clip.mp4',
|
||||
},
|
||||
}
|
||||
expect(serializeContextToXml(context)).toBe(
|
||||
'<context>\n <current_asset id="ast_1" name="clip.mp4" type="file" media_type="video" path="clip.mp4" />\n</context>',
|
||||
)
|
||||
})
|
||||
|
||||
it('serializes full video context with duration, timestamp, annotation, attached files, and referenced assets', () => {
|
||||
const context: ShumaiMessageContext = {
|
||||
user: { id: 'usr_01', name: 'Alice Chen', role: 'editor' },
|
||||
currentAsset: {
|
||||
id: 'ast_01JC04_CURRENT',
|
||||
name: 'product_launch_v2.mp4',
|
||||
type: 'file',
|
||||
mediaType: 'video',
|
||||
parentId: 'ast_01JC03_PARENT',
|
||||
path: 'Marketing/2026_Launch/Footage/product_launch_v2.mp4',
|
||||
durationSeconds: 85.4,
|
||||
ancestors: [
|
||||
{ id: 'ast_01JC01_ROOT', name: 'Marketing' },
|
||||
{ id: 'ast_01JC02_SUB', name: '2026_Launch' },
|
||||
{ id: 'ast_01JC03_PARENT', name: 'Footage' },
|
||||
],
|
||||
},
|
||||
position: { type: 'time', seconds: 14.25 },
|
||||
annotation: true,
|
||||
attachedFiles: [
|
||||
{
|
||||
id: 'ast_01JC05_ATT1',
|
||||
name: 'brand_guidelines_2026.pdf',
|
||||
type: 'file',
|
||||
mediaType: 'pdf',
|
||||
path: 'Brand/brand_guidelines_2026.pdf',
|
||||
},
|
||||
],
|
||||
referencedAssets: [
|
||||
{
|
||||
id: 'ast_01JC07_REF2',
|
||||
name: 'Color_LUTs',
|
||||
type: 'folder',
|
||||
path: 'Assets/Color_LUTs',
|
||||
},
|
||||
{
|
||||
id: 'ast_01JC06_REF1',
|
||||
name: 'logo_white.png',
|
||||
type: 'file',
|
||||
mediaType: 'image',
|
||||
path: 'Brand/Logos/logo_white.png',
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
const expected = `<context>
|
||||
<user id="usr_01" name="Alice Chen" role="editor" />
|
||||
<current_asset id="ast_01JC04_CURRENT" name="product_launch_v2.mp4" type="file" media_type="video" parent_id="ast_01JC03_PARENT" path="Marketing/2026_Launch/Footage/product_launch_v2.mp4" duration_seconds="85.40">
|
||||
<ancestors>
|
||||
<folder id="ast_01JC01_ROOT" name="Marketing" />
|
||||
<folder id="ast_01JC02_SUB" name="2026_Launch" />
|
||||
<folder id="ast_01JC03_PARENT" name="Footage" />
|
||||
</ancestors>
|
||||
</current_asset>
|
||||
<position type="time" seconds="14.25" />
|
||||
<annotation />
|
||||
<attached_files>
|
||||
<file id="ast_01JC05_ATT1" name="brand_guidelines_2026.pdf" type="file" media_type="pdf" path="Brand/brand_guidelines_2026.pdf" />
|
||||
</attached_files>
|
||||
<referenced_assets>
|
||||
<asset id="ast_01JC06_REF1" name="logo_white.png" type="file" media_type="image" path="Brand/Logos/logo_white.png" />
|
||||
<folder id="ast_01JC07_REF2" name="Color_LUTs" path="Assets/Color_LUTs" />
|
||||
</referenced_assets>
|
||||
</context>`
|
||||
|
||||
expect(serializeContextToXml(context)).toBe(expected)
|
||||
})
|
||||
|
||||
it('serializes PDF document context with total_pages and position.type === "page"', () => {
|
||||
const context: ShumaiMessageContext = {
|
||||
currentAsset: {
|
||||
id: 'pdf_1',
|
||||
name: 'report.pdf',
|
||||
type: 'file',
|
||||
mediaType: 'pdf',
|
||||
totalPages: 12,
|
||||
},
|
||||
position: { type: 'page', page: 3 },
|
||||
}
|
||||
|
||||
const expected = `<context>
|
||||
<current_asset id="pdf_1" name="report.pdf" type="file" media_type="pdf" total_pages="12" />
|
||||
<position type="page" page="3" />
|
||||
</context>`
|
||||
|
||||
expect(serializeContextToXml(context)).toBe(expected)
|
||||
})
|
||||
|
||||
it('serializes Video context with total_frames and duration_seconds', () => {
|
||||
const context: ShumaiMessageContext = {
|
||||
currentAsset: {
|
||||
id: 'vid_1',
|
||||
name: 'clip.mp4',
|
||||
type: 'file',
|
||||
mediaType: 'video',
|
||||
mimeType: 'video/mp4',
|
||||
durationSeconds: 9,
|
||||
totalFrames: 268,
|
||||
},
|
||||
}
|
||||
|
||||
const expected = `<context>
|
||||
<current_asset id="vid_1" name="clip.mp4" type="file" media_type="video" mime_type="video/mp4" duration_seconds="9.00" total_frames="268" />
|
||||
</context>`
|
||||
|
||||
expect(serializeContextToXml(context)).toBe(expected)
|
||||
})
|
||||
|
||||
it('serializes navigation context with navigated="true" and ancestors hierarchy', () => {
|
||||
const context: ShumaiMessageContext = {
|
||||
currentAsset: {
|
||||
id: 'f_sub',
|
||||
name: 'Subfolder',
|
||||
type: 'folder',
|
||||
navigated: true,
|
||||
ancestors: [{ id: 'f_root', name: 'Root' }],
|
||||
},
|
||||
}
|
||||
|
||||
const expected = `<context>
|
||||
<current_asset id="f_sub" name="Subfolder" type="folder" navigated="true">
|
||||
<ancestors>
|
||||
<folder id="f_root" name="Root" />
|
||||
</ancestors>
|
||||
</current_asset>
|
||||
</context>`
|
||||
|
||||
expect(serializeContextToXml(context)).toBe(expected)
|
||||
})
|
||||
|
||||
it('serializes mime_type alongside media_type for current asset and attached files', () => {
|
||||
const context: ShumaiMessageContext = {
|
||||
currentAsset: {
|
||||
id: 'img_1',
|
||||
name: 'photo.png',
|
||||
type: 'file',
|
||||
mediaType: 'image',
|
||||
mimeType: 'image/png',
|
||||
},
|
||||
attachedFiles: [
|
||||
{
|
||||
id: 'doc_1',
|
||||
name: 'spec.pdf',
|
||||
type: 'file',
|
||||
mediaType: 'pdf',
|
||||
mimeType: 'application/pdf',
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
const expected = `<context>
|
||||
<current_asset id="img_1" name="photo.png" type="file" media_type="image" mime_type="image/png" />
|
||||
<attached_files>
|
||||
<file id="doc_1" name="spec.pdf" type="file" media_type="pdf" mime_type="application/pdf" />
|
||||
</attached_files>
|
||||
</context>`
|
||||
|
||||
expect(serializeContextToXml(context)).toBe(expected)
|
||||
})
|
||||
})
|
||||
|
||||
describe('XML Escaping & Security', () => {
|
||||
it('escapes user names, asset names, and paths with special characters', () => {
|
||||
const context: ShumaiMessageContext = {
|
||||
user: {
|
||||
id: 'u_1',
|
||||
name: 'Alice & Bob <Admin>',
|
||||
role: 'reviewer "lead"',
|
||||
},
|
||||
currentAsset: {
|
||||
id: 'ast_1',
|
||||
name: 'Final <Cut> "v2" & Test.mp4',
|
||||
type: 'file',
|
||||
path: 'Folder A > Folder B & C/clip.mp4',
|
||||
ancestors: [{ id: 'anc_1', name: 'Folder B & C' }],
|
||||
},
|
||||
attachedFiles: [
|
||||
{
|
||||
id: 'att_1',
|
||||
name: "Don't <Touch> & Go.pdf",
|
||||
type: 'file',
|
||||
path: "Path 'A' & 'B'/doc.pdf",
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
const xml = serializeContextToXml(context)
|
||||
expect(xml).toContain('name="Alice & Bob <Admin>"')
|
||||
expect(xml).toContain('role="reviewer "lead""')
|
||||
expect(xml).toContain('name="Final <Cut> "v2" & Test.mp4"')
|
||||
expect(xml).toContain('path="Folder A > Folder B & C/clip.mp4"')
|
||||
expect(xml).toContain('name="Folder B & C"')
|
||||
expect(xml).toContain('name="Don't <Touch> & Go.pdf"')
|
||||
expect(xml).toContain('path="Path 'A' & 'B'/doc.pdf"')
|
||||
|
||||
// Verify no unescaped dangerous characters exist inside attribute quotes
|
||||
const attrMatch = xml.match(/\w+="([^"]*)"/g)
|
||||
expect(attrMatch).not.toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('Order Stability & Prompt Caching Invariants', () => {
|
||||
it('produces identical XML regardless of object key order', () => {
|
||||
const contextA: ShumaiMessageContext = {
|
||||
user: { role: 'editor', name: 'Alice', id: 'u_1' },
|
||||
currentAsset: {
|
||||
name: 'video.mp4',
|
||||
type: 'file',
|
||||
id: 'ast_1',
|
||||
mediaType: 'video',
|
||||
},
|
||||
position: { seconds: 12.345, type: 'time' },
|
||||
}
|
||||
|
||||
const contextB: ShumaiMessageContext = {
|
||||
position: { type: 'time', seconds: 12.345 },
|
||||
currentAsset: {
|
||||
id: 'ast_1',
|
||||
mediaType: 'video',
|
||||
type: 'file',
|
||||
name: 'video.mp4',
|
||||
},
|
||||
user: { id: 'u_1', name: 'Alice', role: 'editor' },
|
||||
}
|
||||
|
||||
expect(serializeContextToXml(contextA)).toBe(serializeContextToXml(contextB))
|
||||
})
|
||||
|
||||
it('sorts attachedFiles and referencedAssets by id ascending', () => {
|
||||
const context: ShumaiMessageContext = {
|
||||
attachedFiles: [
|
||||
{ id: 'z_file', name: 'Z', type: 'file' },
|
||||
{ id: 'a_file', name: 'A', type: 'file' },
|
||||
{ id: 'm_file', name: 'M', type: 'file' },
|
||||
],
|
||||
referencedAssets: [
|
||||
{ id: 'z_asset', name: 'Z', type: 'file' },
|
||||
{ id: 'a_asset', name: 'A', type: 'folder' },
|
||||
{ id: 'm_asset', name: 'M', type: 'file' },
|
||||
],
|
||||
}
|
||||
|
||||
const xml = serializeContextToXml(context)
|
||||
const fileOrder = [...xml.matchAll(/<file id="([^"]+)"/g)].map((m) => m[1])
|
||||
const refOrder = [...xml.matchAll(/<(?:asset|folder) id="([^"]+)"/g)].map((m) => m[1])
|
||||
|
||||
expect(fileOrder).toEqual(['a_file', 'm_file', 'z_file'])
|
||||
expect(refOrder).toEqual(['a_asset', 'm_asset', 'z_asset'])
|
||||
})
|
||||
|
||||
it('normalizes float formatting with fixed .toFixed(2)', () => {
|
||||
const context1: ShumaiMessageContext = {
|
||||
currentAsset: { id: '1', name: 'a', type: 'file', durationSeconds: 14 },
|
||||
position: { type: 'time', seconds: 5.5 },
|
||||
}
|
||||
const context2: ShumaiMessageContext = {
|
||||
currentAsset: { id: '1', name: 'a', type: 'file', durationSeconds: 14.0001 },
|
||||
position: { type: 'time', seconds: 5.50002 },
|
||||
}
|
||||
|
||||
expect(serializeContextToXml(context1)).toContain('duration_seconds="14.00"')
|
||||
expect(serializeContextToXml(context1)).toContain('seconds="5.50"')
|
||||
expect(serializeContextToXml(context2)).toContain('duration_seconds="14.00"')
|
||||
expect(serializeContextToXml(context2)).toContain('seconds="5.50"')
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1 @@
|
||||
export { escapeXmlAttr, serializeContextToXml } from '@shumai/dtos'
|
||||
@@ -662,5 +662,85 @@ describe('DatabaseSessionStorage', () => {
|
||||
expect(stats.totalTokens).toBe(170)
|
||||
expect(stats.costTotal).toBeCloseTo(0.032)
|
||||
})
|
||||
|
||||
it('should save user message turn as custom_message (shumai_message) in DB when currentMessageContext is set', async () => {
|
||||
const { agent, user } = await setupTestData()
|
||||
const storage = await DatabaseSessionStorage.create({ agentId: agent.id, userId: user.id })
|
||||
|
||||
storage.currentMessageContext = {
|
||||
user: { id: user.id, name: user.name, role: 'owner' },
|
||||
currentAsset: { id: 'asset-123', name: 'video.mp4', type: 'file' },
|
||||
}
|
||||
|
||||
const userEntry: SessionTreeEntry = {
|
||||
type: 'message',
|
||||
id: 'msg-user-1',
|
||||
parentId: null,
|
||||
timestamp: new Date().toISOString(),
|
||||
message: {
|
||||
role: 'user',
|
||||
content: 'Hello, help me analyze this video',
|
||||
timestamp: Date.now(),
|
||||
},
|
||||
}
|
||||
|
||||
await storage.appendEntry(userEntry)
|
||||
|
||||
// 1. Verify DB record type is 'custom_message', not 'message'
|
||||
const record = await prisma.agentSessionEntry.findUnique({
|
||||
where: { id: 'msg-user-1' },
|
||||
})
|
||||
expect(record).toBeDefined()
|
||||
expect(record?.type).toBe('custom_message')
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const data = record?.data as any
|
||||
expect(data.customType).toBe('shumai_message')
|
||||
expect(data.content).toBe('Hello, help me analyze this video')
|
||||
expect(data.details?.user?.id).toBe(user.id)
|
||||
expect(data.details?.currentAsset?.id).toBe('asset-123')
|
||||
|
||||
// 2. Verify getEntries() and getPathToRoot() do not throw and return proper custom_message
|
||||
const entries = await storage.getEntries()
|
||||
expect(entries).toHaveLength(1)
|
||||
expect(entries[0].type).toBe('custom_message')
|
||||
|
||||
const pathEntries = await storage.getPathToRoot('msg-user-1')
|
||||
expect(pathEntries).toHaveLength(1)
|
||||
expect(pathEntries[0].type).toBe('custom_message')
|
||||
|
||||
const stats = await storage.getSessionStats()
|
||||
expect(stats.messageCount).toBe(1)
|
||||
})
|
||||
|
||||
it('should safely handle legacy records where type was message but data was shumai_message', async () => {
|
||||
const { agent } = await setupTestData()
|
||||
const storage = await DatabaseSessionStorage.create({ agentId: agent.id })
|
||||
|
||||
await prisma.agentSessionEntry.create({
|
||||
data: {
|
||||
id: 'legacy-corrupted-entry',
|
||||
sessionId: storage.sessionId,
|
||||
type: 'message',
|
||||
data: {
|
||||
customType: 'shumai_message',
|
||||
content: 'Legacy prompt',
|
||||
display: true,
|
||||
details: { user: { id: 'u1', name: 'User 1' } },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
// Must not throw in getEntries(), getPathToRoot(), or getSessionStats()
|
||||
const entries = await storage.getEntries()
|
||||
expect(entries).toHaveLength(1)
|
||||
expect(entries[0].type).toBe('custom_message')
|
||||
|
||||
const path = await storage.getPathToRoot('legacy-corrupted-entry')
|
||||
expect(path).toHaveLength(1)
|
||||
expect(path[0].type).toBe('custom_message')
|
||||
|
||||
const stats = await storage.getSessionStats()
|
||||
expect(stats.messageCount).toBe(1)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -72,6 +72,7 @@ export class DatabaseSessionStorage implements SessionStorage<DatabaseSessionMet
|
||||
}
|
||||
|
||||
nextEntryId?: string | null
|
||||
currentMessageContext?: PrismaJson.ShumaiMessageContext
|
||||
|
||||
async createEntryId(): Promise<string> {
|
||||
if (this.nextEntryId) {
|
||||
@@ -90,9 +91,13 @@ export class DatabaseSessionStorage implements SessionStorage<DatabaseSessionMet
|
||||
data: unknown
|
||||
}): SessionTreeEntry {
|
||||
const payload = (record.data as Record<string, unknown>) || {}
|
||||
let type = (record.type || 'message') as SessionTreeEntry['type']
|
||||
if (type === 'message' && payload.customType === 'shumai_message') {
|
||||
type = 'custom_message'
|
||||
}
|
||||
return {
|
||||
id: record.id,
|
||||
type: (record.type || 'message') as SessionTreeEntry['type'],
|
||||
type,
|
||||
parentId: record.parentId,
|
||||
timestamp: record.createdAt.toISOString(),
|
||||
...payload,
|
||||
@@ -100,10 +105,41 @@ export class DatabaseSessionStorage implements SessionStorage<DatabaseSessionMet
|
||||
}
|
||||
|
||||
async appendEntry(entry: SessionTreeEntry): Promise<void> {
|
||||
const strippedEntry = structuredClone(entry)
|
||||
let entryToProcess = entry
|
||||
if (
|
||||
entryToProcess.type === 'message' &&
|
||||
entryToProcess.message &&
|
||||
entryToProcess.message.role === 'user' &&
|
||||
this.currentMessageContext
|
||||
) {
|
||||
let contentText = ''
|
||||
if (typeof entryToProcess.message.content === 'string') {
|
||||
contentText = entryToProcess.message.content
|
||||
} else if (Array.isArray(entryToProcess.message.content)) {
|
||||
contentText = entryToProcess.message.content
|
||||
.map((c) =>
|
||||
typeof c === 'object' && c && 'text' in c && typeof c.text === 'string' ? c.text : '',
|
||||
)
|
||||
.join('')
|
||||
}
|
||||
|
||||
entryToProcess = {
|
||||
type: 'custom_message',
|
||||
id: entryToProcess.id,
|
||||
parentId: entryToProcess.parentId,
|
||||
timestamp: entryToProcess.timestamp,
|
||||
customType: 'shumai_message',
|
||||
content: contentText,
|
||||
display: true,
|
||||
details: this.currentMessageContext,
|
||||
} as unknown as SessionTreeEntry
|
||||
this.currentMessageContext = undefined
|
||||
}
|
||||
|
||||
const strippedEntry = structuredClone(entryToProcess)
|
||||
|
||||
// Strip image data and skill content before saving to DB
|
||||
if (strippedEntry.type === 'message') {
|
||||
if (strippedEntry.type === 'message' && strippedEntry.message) {
|
||||
const msg = strippedEntry.message
|
||||
if (msg.role === 'toolResult') {
|
||||
const details = msg.details as { sourceKeys?: string[]; skillId?: string } | undefined
|
||||
@@ -139,7 +175,10 @@ export class DatabaseSessionStorage implements SessionStorage<DatabaseSessionMet
|
||||
}
|
||||
}
|
||||
|
||||
const targetLeafId = entry.type === 'leaf' ? entry.targetId : entry.id
|
||||
const targetLeafId =
|
||||
strippedEntry.type === 'leaf'
|
||||
? (strippedEntry as unknown as { targetId?: string }).targetId || strippedEntry.id
|
||||
: strippedEntry.id
|
||||
|
||||
// Extract base fields and store type-specific properties in data payload
|
||||
const payload = { ...strippedEntry } as Record<string, unknown>
|
||||
@@ -155,17 +194,18 @@ export class DatabaseSessionStorage implements SessionStorage<DatabaseSessionMet
|
||||
|
||||
await prisma.$transaction([
|
||||
prisma.agentSessionEntry.upsert({
|
||||
where: { id: entry.id },
|
||||
where: { id: strippedEntry.id },
|
||||
create: {
|
||||
id: entry.id,
|
||||
id: strippedEntry.id,
|
||||
sessionId: this.sessionId,
|
||||
assetId: session?.assetId || null,
|
||||
type: entry.type,
|
||||
parentId: entry.parentId || null,
|
||||
createdAt: entry.timestamp ? new Date(entry.timestamp) : new Date(),
|
||||
type: strippedEntry.type,
|
||||
parentId: strippedEntry.parentId || null,
|
||||
createdAt: strippedEntry.timestamp ? new Date(strippedEntry.timestamp) : new Date(),
|
||||
data: payload as PrismaJson.PiSessionEntryData,
|
||||
},
|
||||
update: {
|
||||
type: strippedEntry.type,
|
||||
data: payload as PrismaJson.PiSessionEntryData,
|
||||
},
|
||||
}),
|
||||
@@ -236,7 +276,9 @@ export class DatabaseSessionStorage implements SessionStorage<DatabaseSessionMet
|
||||
let costTotal = 0
|
||||
|
||||
for (const entry of entries) {
|
||||
if (entry.type === 'message') {
|
||||
if (entry.type === 'custom_message' && entry.customType === 'shumai_message') {
|
||||
messageCount++
|
||||
} else if (entry.type === 'message' && entry.message) {
|
||||
const msg = entry.message
|
||||
if (msg.role === 'user' || msg.role === 'assistant') {
|
||||
messageCount++
|
||||
@@ -348,18 +390,29 @@ export class DatabaseSessionStorage implements SessionStorage<DatabaseSessionMet
|
||||
for (let i = 0; i < pathEntries.length; i++) {
|
||||
const entry = pathEntries[i]
|
||||
const count = threadReplyCountMap.get(entry.id)
|
||||
if (count !== undefined && count > 0 && entry.type === 'message') {
|
||||
const cloned = structuredClone(entry)
|
||||
const msg = cloned.message as unknown as {
|
||||
content?: Array<{ type: string; text: string }>
|
||||
}
|
||||
if (Array.isArray(msg.content) && msg.content[0] && msg.content[0].type === 'text') {
|
||||
const threadTag = `[Thread ID: ${entry.id}] [Replies: ${count}]`
|
||||
if (!msg.content[0].text.includes(`[Thread ID: ${entry.id}]`)) {
|
||||
msg.content[0].text = `${threadTag} ${msg.content[0].text}`
|
||||
if (count !== undefined && count > 0) {
|
||||
if (entry.type === 'message' && entry.message) {
|
||||
const cloned = structuredClone(entry)
|
||||
const msg = cloned.message as unknown as {
|
||||
content?: Array<{ type: string; text: string }>
|
||||
}
|
||||
if (Array.isArray(msg.content) && msg.content[0] && msg.content[0].type === 'text') {
|
||||
const threadTag = `[Thread ID: ${entry.id}] [Replies: ${count}]`
|
||||
if (!msg.content[0].text.includes(`[Thread ID: ${entry.id}]`)) {
|
||||
msg.content[0].text = `${threadTag} ${msg.content[0].text}`
|
||||
}
|
||||
}
|
||||
pathEntries[i] = cloned
|
||||
} else if (entry.type === 'custom_message') {
|
||||
const cloned = structuredClone(entry)
|
||||
const threadTag = `[Thread ID: ${entry.id}] [Replies: ${count}]`
|
||||
if (typeof cloned.content === 'string') {
|
||||
if (!cloned.content.includes(`[Thread ID: ${entry.id}]`)) {
|
||||
cloned.content = `${threadTag} ${cloned.content}`
|
||||
}
|
||||
}
|
||||
pathEntries[i] = cloned
|
||||
}
|
||||
pathEntries[i] = cloned
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -382,7 +435,7 @@ export class DatabaseSessionStorage implements SessionStorage<DatabaseSessionMet
|
||||
}
|
||||
|
||||
private async reinjectImageDataAsync(entry: SessionTreeEntry) {
|
||||
if (entry.type === 'message') {
|
||||
if (entry.type === 'message' && entry.message) {
|
||||
const msg = entry.message as AgentMessage
|
||||
if (msg.role === 'toolResult') {
|
||||
const details = msg.details as { sourceKeys?: string[] } | undefined
|
||||
@@ -407,7 +460,7 @@ export class DatabaseSessionStorage implements SessionStorage<DatabaseSessionMet
|
||||
}
|
||||
|
||||
private async reinjectSkillContentAsync(entry: SessionTreeEntry) {
|
||||
if (entry.type === 'message') {
|
||||
if (entry.type === 'message' && entry.message) {
|
||||
const msg = entry.message as AgentMessage
|
||||
if (msg.role === 'toolResult' && msg.toolName === 'read_skill') {
|
||||
const details = msg.details as { skillId?: string } | undefined
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
+89
-25
@@ -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'
|
||||
@@ -27,6 +30,8 @@ import { createReadSkillTool } from './tools/read-skill'
|
||||
import { createReadThreadTool } from './tools/read-thread'
|
||||
import { createSandboxedBashTool } from './tools/sandboxed-bash'
|
||||
import { createScreenshotTool } from './tools/screenshot'
|
||||
import { serializeContextToXml } from './context/serialize-context'
|
||||
import type { ShumaiMessageContext } from '@shumai/dtos'
|
||||
|
||||
export interface DbModelInfo {
|
||||
modelId: string
|
||||
@@ -112,18 +117,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 +178,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 +213,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 +286,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) {
|
||||
@@ -257,6 +294,7 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
|
||||
for (const entry of entries) {
|
||||
if (
|
||||
entry.type === 'message' &&
|
||||
entry.message &&
|
||||
entry.message.role === 'toolResult' &&
|
||||
entry.message.toolName === 'read_skill' &&
|
||||
!entry.message.isError
|
||||
@@ -294,6 +332,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 +355,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 +366,7 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
|
||||
onEnvsAdded,
|
||||
restricted ? onSkillLoaded : undefined,
|
||||
enabledSkillIds,
|
||||
projectId,
|
||||
)
|
||||
|
||||
const systemTools: AgentTool[] = []
|
||||
@@ -340,7 +382,7 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
|
||||
}
|
||||
|
||||
const readThread = createReadThreadTool()
|
||||
const allTools = [
|
||||
const rawTools = [
|
||||
...mediaTools,
|
||||
readSkill,
|
||||
readThread,
|
||||
@@ -348,6 +390,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))
|
||||
@@ -405,6 +448,29 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
|
||||
tools: enabledTools,
|
||||
})
|
||||
|
||||
harness.on('context', async ({ messages }) => {
|
||||
return {
|
||||
messages: messages.map((msg) => {
|
||||
if (
|
||||
msg.role === 'custom' &&
|
||||
msg.customType === 'shumai_message' &&
|
||||
msg.details &&
|
||||
typeof msg.details === 'object'
|
||||
) {
|
||||
const context = msg.details as ShumaiMessageContext
|
||||
const xml = serializeContextToXml(context)
|
||||
const text = typeof msg.content === 'string' ? msg.content : ''
|
||||
const fullContent = xml ? `${text}\n\n${xml}`.trim() : text
|
||||
return {
|
||||
...msg,
|
||||
content: fullContent,
|
||||
}
|
||||
}
|
||||
return msg
|
||||
}),
|
||||
}
|
||||
})
|
||||
|
||||
return { session, harness }
|
||||
}
|
||||
|
||||
@@ -573,7 +639,6 @@ import * as aiActivities from './activities/ai'
|
||||
import { agentAutofillMedia } from './workflows/agent-autofill'
|
||||
import { agentChat } from './workflows/agent-chat'
|
||||
import { agentEmbeddingMedia } from './workflows/agent-embedding'
|
||||
import { agentToolCall } from './workflows/agent-tool-call'
|
||||
import { queryEmbeddingForSearch } from './workflows/query-embedding-for-search'
|
||||
|
||||
export function initAgentWorkflows() {
|
||||
@@ -581,7 +646,6 @@ export function initAgentWorkflows() {
|
||||
registerWorkflow(WorkflowTaskType.query_embedding_for_search, queryEmbeddingForSearch)
|
||||
registerWorkflow(WorkflowTaskType.ai_metadata_autofill, agentAutofillMedia)
|
||||
registerWorkflow(WorkflowTaskType.chat, agentChat)
|
||||
registerWorkflow(WorkflowTaskType.agent_tool_call, agentToolCall)
|
||||
|
||||
registerActivities(agentActivities)
|
||||
registerActivities(aiActivities)
|
||||
@@ -600,8 +664,8 @@ export {
|
||||
type GenerateTextEmbeddingParams,
|
||||
} from './activities/ai'
|
||||
export * from './database-session-storage'
|
||||
export * from './context/serialize-context'
|
||||
export * from './workflows/agent-autofill'
|
||||
export * from './workflows/agent-chat'
|
||||
export * from './workflows/agent-embedding'
|
||||
export * from './workflows/agent-tool-call'
|
||||
export * from './workflows/query-embedding-for-search'
|
||||
|
||||
@@ -3,7 +3,8 @@ import { validateToolArguments } from '@earendil-works/pi-ai'
|
||||
import { createCreateFileTool } from './tools/create-file'
|
||||
import { fieldsToTypeBoxSchema } from './index'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { executeAgentToolWorkflow } from './tools/utils'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { authzService } from '@shumai/core/src/authz/authz'
|
||||
|
||||
vi.mock('@shumai/core/src/s3/s3', () => ({
|
||||
s3Service: {
|
||||
@@ -12,8 +13,20 @@ vi.mock('@shumai/core/src/s3/s3', () => ({
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('./tools/utils', () => ({
|
||||
executeAgentToolWorkflow: vi.fn().mockResolvedValue({ id: 'file-1', name: 'test', type: 'file' }),
|
||||
vi.mock('@shumai/core/src/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
Permission: { Edit: 'edit', Read: 'read' },
|
||||
ResourceType: { Asset: 'asset' },
|
||||
}))
|
||||
|
||||
vi.mock('@shumai/core/src/asset/asset', () => ({
|
||||
assetService: {
|
||||
createFile: vi
|
||||
.fn()
|
||||
.mockResolvedValue({ id: 'file-1', name: 'test', type: 'file', sizeByte: 100 }),
|
||||
},
|
||||
}))
|
||||
|
||||
/**
|
||||
@@ -63,9 +76,10 @@ describe('reproduce null coercion in harness tool validation', () => {
|
||||
|
||||
// execute must accept the valid call (data-only) without throwing
|
||||
const result = await tool.execute('call-1', validated as never)
|
||||
expect(result.details).toEqual({ id: 'file-1', name: 'test', type: 'file' })
|
||||
expect(result.details).toEqual({ id: 'file-1', name: 'test', type: 'file', size: 100 })
|
||||
expect(s3Service.putObject).toHaveBeenCalledTimes(1)
|
||||
expect(executeAgentToolWorkflow).toHaveBeenCalledTimes(1)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledTimes(1)
|
||||
expect(assetService.createFile).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('keeps null metadata values (the "unknown" sentinel) through validation', () => {
|
||||
|
||||
@@ -2,7 +2,8 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { createCreateFileTool } from './create-file'
|
||||
import { fieldsToTypeBoxSchema } from '../index'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { executeAgentToolWorkflow } from './utils'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { authzService } from '@shumai/core/src/authz/authz'
|
||||
import { Value } from 'typebox/value'
|
||||
import * as fs from 'fs'
|
||||
import * as os from 'os'
|
||||
@@ -15,8 +16,20 @@ vi.mock('@shumai/core/src/s3/s3', () => ({
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('./utils', () => ({
|
||||
executeAgentToolWorkflow: vi.fn().mockResolvedValue({ id: 'file-1', name: 'test', type: 'file' }),
|
||||
vi.mock('@shumai/core/src/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
Permission: { Edit: 'edit', Read: 'read' },
|
||||
ResourceType: { Asset: 'asset' },
|
||||
}))
|
||||
|
||||
vi.mock('@shumai/core/src/asset/asset', () => ({
|
||||
assetService: {
|
||||
createFile: vi
|
||||
.fn()
|
||||
.mockResolvedValue({ id: 'file-1', name: 'test', type: 'file', sizeByte: 100 }),
|
||||
},
|
||||
}))
|
||||
|
||||
describe('createCreateFileTool', () => {
|
||||
@@ -56,23 +69,27 @@ describe('createCreateFileTool', () => {
|
||||
expect(s3Key).toMatch(/^files\/.+\.md$/)
|
||||
expect(uploadArgs[2]).toBe('text/markdown')
|
||||
|
||||
expect(executeAgentToolWorkflow).toHaveBeenCalledWith({
|
||||
toolName: 'create_file',
|
||||
args: {
|
||||
parent: 'folder-1',
|
||||
s3Key,
|
||||
name: 'create-file-test.md',
|
||||
size: Buffer.byteLength('# Hello from disk', 'utf-8'),
|
||||
contentType: 'text/markdown',
|
||||
},
|
||||
userId: 'user-1',
|
||||
assetId: 'folder-1',
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: { id: 'user-1' },
|
||||
permission: 'edit',
|
||||
type: 'asset',
|
||||
id: 'folder-1',
|
||||
})
|
||||
|
||||
expect(result.details).toEqual({ id: 'file-1', name: 'test', type: 'file' })
|
||||
expect(assetService.createFile).toHaveBeenCalledWith({
|
||||
parentId: 'folder-1',
|
||||
name: 'create-file-test.md',
|
||||
key: s3Key,
|
||||
sizeByte: Buffer.byteLength('# Hello from disk', 'utf-8'),
|
||||
contentType: 'text/markdown',
|
||||
creatorId: 'user-1',
|
||||
metadata: undefined,
|
||||
})
|
||||
|
||||
expect(result.details).toEqual({ id: 'file-1', name: 'test', type: 'file', size: 100 })
|
||||
})
|
||||
|
||||
it('should forward the metadata to the agent tool workflow when provided', async () => {
|
||||
it('should forward the metadata to assetService.createFile when provided', async () => {
|
||||
const filePath = createTempFile('# Hello from disk', 'create-file-metadata.md')
|
||||
const metadataSchema = fieldsToTypeBoxSchema([
|
||||
{ id: 'prompt', config: { name: 'Prompt', type: 'text' } },
|
||||
@@ -86,9 +103,9 @@ describe('createCreateFileTool', () => {
|
||||
metadata: { prompt: 'Generated using gemini' },
|
||||
})
|
||||
|
||||
expect(executeAgentToolWorkflow).toHaveBeenCalledWith(
|
||||
expect(assetService.createFile).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
args: expect.objectContaining({ metadata: { prompt: 'Generated using gemini' } }),
|
||||
metadata: { prompt: 'Generated using gemini' },
|
||||
}),
|
||||
)
|
||||
})
|
||||
@@ -125,19 +142,17 @@ describe('createCreateFileTool', () => {
|
||||
},
|
||||
})
|
||||
|
||||
expect(executeAgentToolWorkflow).toHaveBeenCalledWith(
|
||||
expect(assetService.createFile).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
args: expect.objectContaining({
|
||||
metadata: {
|
||||
provider: { newOption: { value: 'Kling' } },
|
||||
tags: ['tag1', { newOption: { value: 'Tag 2' } }],
|
||||
},
|
||||
}),
|
||||
metadata: {
|
||||
provider: { newOption: { value: 'Kling' } },
|
||||
tags: ['tag1', { newOption: { value: 'Tag 2' } }],
|
||||
},
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('should not include metadata in args when metadata is null', async () => {
|
||||
it('should not include metadata when metadata is null', async () => {
|
||||
const filePath = createTempFile('# Hello from disk', 'create-file-no-metadata.md')
|
||||
const metadataSchema = fieldsToTypeBoxSchema([
|
||||
{ id: 'prompt', config: { name: 'Prompt', type: 'text' } },
|
||||
@@ -151,8 +166,8 @@ describe('createCreateFileTool', () => {
|
||||
metadata: null,
|
||||
})
|
||||
|
||||
const callArgs = vi.mocked(executeAgentToolWorkflow).mock.calls[0][0].args
|
||||
expect(callArgs).not.toHaveProperty('metadata')
|
||||
const callArgs = vi.mocked(assetService.createFile).mock.calls[0][0]
|
||||
expect(callArgs.metadata).toBeUndefined()
|
||||
})
|
||||
|
||||
it('should throw when the local file does not exist', async () => {
|
||||
@@ -161,7 +176,7 @@ describe('createCreateFileTool', () => {
|
||||
tool.execute('call-1', { parent: 'folder-1', path: '/nonexistent/file.md', data: null }),
|
||||
).rejects.toThrow('Local file not found at path: /nonexistent/file.md')
|
||||
expect(s3Service.uploadFileToKey).not.toHaveBeenCalled()
|
||||
expect(executeAgentToolWorkflow).not.toHaveBeenCalled()
|
||||
expect(assetService.createFile).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should create a file directly from name and content', async () => {
|
||||
@@ -184,20 +199,17 @@ describe('createCreateFileTool', () => {
|
||||
expect(size).toBe(Buffer.byteLength('# Notes\n\nHello', 'utf-8'))
|
||||
expect(contentType).toBe('text/markdown')
|
||||
|
||||
expect(executeAgentToolWorkflow).toHaveBeenCalledWith({
|
||||
toolName: 'create_file',
|
||||
args: {
|
||||
parent: 'folder-1',
|
||||
s3Key,
|
||||
name: 'notes.md',
|
||||
size: Buffer.byteLength('# Notes\n\nHello', 'utf-8'),
|
||||
contentType: 'text/markdown',
|
||||
},
|
||||
userId: 'user-1',
|
||||
assetId: 'folder-1',
|
||||
expect(assetService.createFile).toHaveBeenCalledWith({
|
||||
parentId: 'folder-1',
|
||||
name: 'notes.md',
|
||||
key: s3Key,
|
||||
sizeByte: Buffer.byteLength('# Notes\n\nHello', 'utf-8'),
|
||||
contentType: 'text/markdown',
|
||||
creatorId: 'user-1',
|
||||
metadata: undefined,
|
||||
})
|
||||
|
||||
expect(result.details).toEqual({ id: 'file-1', name: 'test', type: 'file' })
|
||||
expect(result.details).toEqual({ id: 'file-1', name: 'test', type: 'file', size: 100 })
|
||||
})
|
||||
|
||||
it('should default unknown extensions to text/plain when creating from content', async () => {
|
||||
@@ -235,10 +247,8 @@ describe('createCreateFileTool', () => {
|
||||
]
|
||||
expect(s3Key).toContain('my_notes.md')
|
||||
|
||||
expect(executeAgentToolWorkflow).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
args: expect.objectContaining({ name: 'my_notes.md' }),
|
||||
}),
|
||||
expect(assetService.createFile).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ name: 'my_notes.md' }),
|
||||
)
|
||||
})
|
||||
|
||||
@@ -260,7 +270,7 @@ describe('createCreateFileTool', () => {
|
||||
).rejects.toThrow('Provide exactly one of "path" (a local file) or "data" (name and content).')
|
||||
expect(s3Service.uploadFileToKey).not.toHaveBeenCalled()
|
||||
expect(s3Service.putObject).not.toHaveBeenCalled()
|
||||
expect(executeAgentToolWorkflow).not.toHaveBeenCalled()
|
||||
expect(assetService.createFile).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should expose a strict, all-required (nullable) metadata schema when fields are provided', () => {
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
import { type AgentTool } from '@earendil-works/pi-agent-core'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { getFileMimeType, readFileMimeType } from '@shumai/core/src/utils/file-mime'
|
||||
import { sanitizeFilename } from '@shumai/core/src/utils/filename'
|
||||
import { type User } from '@shumai/db'
|
||||
import { Type, type TSchema } from 'typebox'
|
||||
import * as fs from 'fs'
|
||||
import * as path from 'path'
|
||||
import { ulid } from 'ulid'
|
||||
import { executeAgentToolWorkflow } from './utils'
|
||||
|
||||
interface CreateFileToolParams {
|
||||
parent: string
|
||||
@@ -105,19 +107,30 @@ export function createCreateFileTool(userId: string, metadataSchema?: TSchema):
|
||||
await s3Service.putObject(process.env.S3_BUCKET || 'shumai', s3Key, content, size, mimeType)
|
||||
}
|
||||
|
||||
const result = await executeAgentToolWorkflow({
|
||||
toolName: 'create_file',
|
||||
args: {
|
||||
parent: p.parent,
|
||||
s3Key,
|
||||
name,
|
||||
size,
|
||||
contentType: mimeType,
|
||||
...(p.metadata ? { metadata: p.metadata } : {}),
|
||||
},
|
||||
userId,
|
||||
assetId: p.parent,
|
||||
await authzService.hasPermission({
|
||||
user: { id: userId } as User,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: p.parent,
|
||||
})
|
||||
|
||||
const asset = await assetService.createFile({
|
||||
parentId: p.parent,
|
||||
name,
|
||||
key: s3Key,
|
||||
sizeByte: size,
|
||||
contentType: mimeType,
|
||||
creatorId: userId,
|
||||
metadata: p.metadata ?? undefined,
|
||||
})
|
||||
|
||||
const result = {
|
||||
id: asset.id,
|
||||
name: asset.name,
|
||||
type: asset.type,
|
||||
size: Number(asset.sizeByte),
|
||||
}
|
||||
|
||||
return {
|
||||
content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
|
||||
details: result,
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { createCreateFolderTool } from './create-folder'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { authzService } from '@shumai/core/src/authz/authz'
|
||||
|
||||
vi.mock('@shumai/core/src/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
Permission: { Edit: 'edit', Read: 'read' },
|
||||
ResourceType: { Asset: 'asset' },
|
||||
}))
|
||||
|
||||
vi.mock('@shumai/core/src/asset/asset', () => ({
|
||||
assetService: {
|
||||
createAsset: vi.fn().mockResolvedValue({
|
||||
id: 'folder-1',
|
||||
name: 'New Folder',
|
||||
type: 'folder',
|
||||
sizeByte: 0,
|
||||
}),
|
||||
},
|
||||
}))
|
||||
|
||||
describe('createCreateFolderTool', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('checks edit permission and calls assetService.createAsset with folder type', async () => {
|
||||
const tool = createCreateFolderTool('user-1')
|
||||
const result = await tool.execute('call-1', { parent: 'root-folder', name: 'New Folder' })
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: { id: 'user-1' },
|
||||
permission: 'edit',
|
||||
type: 'asset',
|
||||
id: 'root-folder',
|
||||
})
|
||||
|
||||
expect(assetService.createAsset).toHaveBeenCalledWith({
|
||||
name: 'New Folder',
|
||||
parentId: 'root-folder',
|
||||
type: 'folder',
|
||||
creatorId: 'user-1',
|
||||
})
|
||||
|
||||
expect(result.details).toEqual({
|
||||
id: 'folder-1',
|
||||
name: 'New Folder',
|
||||
type: 'folder',
|
||||
size: 0,
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,6 +1,8 @@
|
||||
import { Type } from 'typebox'
|
||||
import { type AgentTool } from '@earendil-works/pi-agent-core'
|
||||
import { executeAgentToolWorkflow } from './utils'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { type User } from '@shumai/db'
|
||||
|
||||
const createFolderSchema = Type.Object({
|
||||
parent: Type.String({
|
||||
@@ -19,12 +21,27 @@ export function createCreateFolderTool(userId: string): AgentTool<typeof createF
|
||||
description: 'Create a new folder in a specified parent folder.',
|
||||
parameters: createFolderSchema,
|
||||
execute: async (_toolCallId, params) => {
|
||||
const result = await executeAgentToolWorkflow({
|
||||
toolName: 'create_folder',
|
||||
args: params,
|
||||
userId,
|
||||
assetId: params.parent,
|
||||
await authzService.hasPermission({
|
||||
user: { id: userId } as User,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: params.parent,
|
||||
})
|
||||
|
||||
const newFolder = await assetService.createAsset({
|
||||
name: params.name,
|
||||
parentId: params.parent,
|
||||
type: 'folder',
|
||||
creatorId: userId,
|
||||
})
|
||||
|
||||
const result = {
|
||||
id: newFolder.id,
|
||||
name: newFolder.name,
|
||||
type: newFolder.type,
|
||||
size: Number(newFolder.sizeByte),
|
||||
}
|
||||
|
||||
return {
|
||||
content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
|
||||
details: result,
|
||||
|
||||
@@ -2,7 +2,8 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { createCreateVersionTool } from './create-version'
|
||||
import { fieldsToTypeBoxSchema } from '../index'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { executeAgentToolWorkflow } from './utils'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { authzService } from '@shumai/core/src/authz/authz'
|
||||
import { Value } from 'typebox/value'
|
||||
import * as fs from 'fs'
|
||||
import * as os from 'os'
|
||||
@@ -14,8 +15,20 @@ vi.mock('@shumai/core/src/s3/s3', () => ({
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('./utils', () => ({
|
||||
executeAgentToolWorkflow: vi.fn().mockResolvedValue({ id: 'file-1', name: 'v2', type: 'file' }),
|
||||
vi.mock('@shumai/core/src/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
Permission: { Edit: 'edit', Read: 'read' },
|
||||
ResourceType: { Asset: 'asset' },
|
||||
}))
|
||||
|
||||
vi.mock('@shumai/core/src/asset/asset', () => ({
|
||||
assetService: {
|
||||
createVersion: vi
|
||||
.fn()
|
||||
.mockResolvedValue({ id: 'file-1', name: 'v2', type: 'file', sizeByte: 100 }),
|
||||
},
|
||||
}))
|
||||
|
||||
describe('createCreateVersionTool', () => {
|
||||
@@ -41,7 +54,7 @@ describe('createCreateVersionTool', () => {
|
||||
return filePath
|
||||
}
|
||||
|
||||
it('should upload a local file and create a version via the agent tool workflow', async () => {
|
||||
it('should upload a local file and create a version via assetService.createVersion', async () => {
|
||||
const filePath = createTempFile('# Hello from disk', 'create-version-test.md')
|
||||
|
||||
const tool = createCreateVersionTool('user-1')
|
||||
@@ -53,23 +66,27 @@ describe('createCreateVersionTool', () => {
|
||||
expect(s3Key).toMatch(/^files\/.+\.md$/)
|
||||
expect(uploadArgs[2]).toBe('text/markdown')
|
||||
|
||||
expect(executeAgentToolWorkflow).toHaveBeenCalledWith({
|
||||
toolName: 'create_version',
|
||||
args: {
|
||||
parent: 'file-1',
|
||||
s3Key,
|
||||
name: 'create-version-test.md',
|
||||
size: Buffer.byteLength('# Hello from disk', 'utf-8'),
|
||||
contentType: 'text/markdown',
|
||||
},
|
||||
userId: 'user-1',
|
||||
assetId: 'file-1',
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: { id: 'user-1' },
|
||||
permission: 'edit',
|
||||
type: 'asset',
|
||||
id: 'file-1',
|
||||
})
|
||||
|
||||
expect(result.details).toEqual({ id: 'file-1', name: 'v2', type: 'file' })
|
||||
expect(assetService.createVersion).toHaveBeenCalledWith({
|
||||
parentId: 'file-1',
|
||||
name: 'create-version-test.md',
|
||||
key: s3Key,
|
||||
sizeByte: Buffer.byteLength('# Hello from disk', 'utf-8'),
|
||||
contentType: 'text/markdown',
|
||||
creatorId: 'user-1',
|
||||
metadata: undefined,
|
||||
})
|
||||
|
||||
expect(result.details).toEqual({ id: 'file-1', name: 'v2', type: 'file', size: 100 })
|
||||
})
|
||||
|
||||
it('should forward the metadata to the agent tool workflow when provided', async () => {
|
||||
it('should forward the metadata to assetService.createVersion when provided', async () => {
|
||||
const filePath = createTempFile('# Hello from disk', 'create-version-metadata.md')
|
||||
const metadataSchema = fieldsToTypeBoxSchema([
|
||||
{ id: 'prompt', config: { name: 'Prompt', type: 'text' } },
|
||||
@@ -82,9 +99,9 @@ describe('createCreateVersionTool', () => {
|
||||
metadata: { prompt: 'Generated using gemini' },
|
||||
})
|
||||
|
||||
expect(executeAgentToolWorkflow).toHaveBeenCalledWith(
|
||||
expect(assetService.createVersion).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
args: expect.objectContaining({ metadata: { prompt: 'Generated using gemini' } }),
|
||||
metadata: { prompt: 'Generated using gemini' },
|
||||
}),
|
||||
)
|
||||
})
|
||||
@@ -120,19 +137,17 @@ describe('createCreateVersionTool', () => {
|
||||
},
|
||||
})
|
||||
|
||||
expect(executeAgentToolWorkflow).toHaveBeenCalledWith(
|
||||
expect(assetService.createVersion).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
args: expect.objectContaining({
|
||||
metadata: {
|
||||
provider: { newOption: { value: 'Kling' } },
|
||||
tags: ['tag1', { newOption: { value: 'Tag 2' } }],
|
||||
},
|
||||
}),
|
||||
metadata: {
|
||||
provider: { newOption: { value: 'Kling' } },
|
||||
tags: ['tag1', { newOption: { value: 'Tag 2' } }],
|
||||
},
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('should not include metadata in args when metadata is null', async () => {
|
||||
it('should not include metadata when metadata is null', async () => {
|
||||
const filePath = createTempFile('# Hello from disk', 'create-version-no-metadata.md')
|
||||
const metadataSchema = fieldsToTypeBoxSchema([
|
||||
{ id: 'prompt', config: { name: 'Prompt', type: 'text' } },
|
||||
@@ -141,8 +156,8 @@ describe('createCreateVersionTool', () => {
|
||||
const tool = createCreateVersionTool('user-1', metadataSchema)
|
||||
await tool.execute('call-1', { parent: 'file-1', path: filePath, metadata: null })
|
||||
|
||||
const callArgs = vi.mocked(executeAgentToolWorkflow).mock.calls[0][0].args
|
||||
expect(callArgs).not.toHaveProperty('metadata')
|
||||
const callArgs = vi.mocked(assetService.createVersion).mock.calls[0][0]
|
||||
expect(callArgs.metadata).toBeUndefined()
|
||||
})
|
||||
|
||||
it('should throw when the local file does not exist', async () => {
|
||||
@@ -151,7 +166,7 @@ describe('createCreateVersionTool', () => {
|
||||
tool.execute('call-1', { parent: 'file-1', path: '/nonexistent/file.md' }),
|
||||
).rejects.toThrow('Local file not found at path: /nonexistent/file.md')
|
||||
expect(s3Service.uploadFileToKey).not.toHaveBeenCalled()
|
||||
expect(executeAgentToolWorkflow).not.toHaveBeenCalled()
|
||||
expect(assetService.createVersion).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should expose a strict, all-required (nullable) metadata schema when fields are provided', () => {
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
import { Type, type TSchema } from 'typebox'
|
||||
import { type AgentTool } from '@earendil-works/pi-agent-core'
|
||||
import { executeAgentToolWorkflow } from './utils'
|
||||
import * as fs from 'fs'
|
||||
import * as path from 'path'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { readFileMimeType } from '@shumai/core/src/utils/file-mime'
|
||||
import { ulid } from 'ulid'
|
||||
import { sanitizeFilename } from '@shumai/core/src/utils/filename'
|
||||
import { type User } from '@shumai/db'
|
||||
import { Type, type TSchema } from 'typebox'
|
||||
import * as fs from 'fs'
|
||||
import * as path from 'path'
|
||||
import { ulid } from 'ulid'
|
||||
|
||||
interface CreateVersionToolParams {
|
||||
parent: string
|
||||
@@ -48,24 +50,36 @@ export function createCreateVersionTool(userId: string, metadataSchema?: TSchema
|
||||
|
||||
const fileSize = fs.statSync(absolutePath).size
|
||||
const mimeType = readFileMimeType(absolutePath)
|
||||
const name = path.basename(absolutePath)
|
||||
|
||||
// Generate compliant S3 key matching normal file upload format
|
||||
const s3Key = `files/${ulid()}/${sanitizeFilename(path.basename(absolutePath))}`
|
||||
const s3Key = `files/${ulid()}/${sanitizeFilename(name)}`
|
||||
await s3Service.uploadFileToKey(absolutePath, s3Key, mimeType)
|
||||
|
||||
const result = await executeAgentToolWorkflow({
|
||||
toolName: 'create_version',
|
||||
args: {
|
||||
parent: p.parent,
|
||||
s3Key,
|
||||
name: path.basename(absolutePath),
|
||||
size: fileSize,
|
||||
contentType: mimeType,
|
||||
...(p.metadata ? { metadata: p.metadata } : {}),
|
||||
},
|
||||
userId,
|
||||
assetId: p.parent,
|
||||
await authzService.hasPermission({
|
||||
user: { id: userId } as User,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: p.parent,
|
||||
})
|
||||
|
||||
const asset = await assetService.createVersion({
|
||||
parentId: p.parent,
|
||||
name,
|
||||
key: s3Key,
|
||||
sizeByte: fileSize,
|
||||
contentType: mimeType,
|
||||
creatorId: userId,
|
||||
metadata: p.metadata ?? undefined,
|
||||
})
|
||||
|
||||
const result = {
|
||||
id: asset.id,
|
||||
name: asset.name,
|
||||
type: asset.type,
|
||||
size: Number(asset.sizeByte),
|
||||
}
|
||||
|
||||
return {
|
||||
content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
|
||||
details: result,
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { createListAssetsTool } from './list-assets'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { authzService } from '@shumai/core/src/authz/authz'
|
||||
|
||||
vi.mock('@shumai/core/src/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
Permission: { Edit: 'edit', Read: 'read' },
|
||||
ResourceType: { Asset: 'asset' },
|
||||
}))
|
||||
|
||||
vi.mock('@shumai/core/src/asset/asset', () => ({
|
||||
assetService: {
|
||||
listChildren: vi.fn().mockResolvedValue({
|
||||
data: [
|
||||
{ id: '01M2FILE2', name: 'file2.txt', type: 'file', sizeByte: 200 },
|
||||
{ id: '01M1FILE1', name: 'file1.txt', type: 'file', sizeByte: 100 },
|
||||
],
|
||||
pageInfo: { hasNextPage: false, hasPreviousPage: false, cursor: 'abc' },
|
||||
}),
|
||||
},
|
||||
}))
|
||||
|
||||
describe('createListAssetsTool', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('checks read permissions and invokes assetService.listChildren with default all and id desc ordering', async () => {
|
||||
const tool = createListAssetsTool('user-1')
|
||||
const result = await tool.execute('call-1', { parent: 'folder-1' })
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: { id: 'user-1' },
|
||||
permission: 'read',
|
||||
type: 'asset',
|
||||
id: 'folder-1',
|
||||
})
|
||||
|
||||
expect(assetService.listChildren).toHaveBeenCalledWith({
|
||||
assetId: 'folder-1',
|
||||
assetType: 'all',
|
||||
sort: 'createdAt',
|
||||
order: 'desc',
|
||||
first: 20,
|
||||
after: undefined,
|
||||
})
|
||||
|
||||
expect(result.details).toEqual({
|
||||
assets: [
|
||||
{ id: '01M2FILE2', name: 'file2.txt', type: 'file', size: 200 },
|
||||
{ id: '01M1FILE1', name: 'file1.txt', type: 'file', size: 100 },
|
||||
],
|
||||
pageInfo: { hasNextPage: false, hasPreviousPage: false, cursor: 'abc' },
|
||||
})
|
||||
})
|
||||
|
||||
it('passes explicit pagination and type filter options to assetService.listChildren', async () => {
|
||||
const tool = createListAssetsTool('user-1')
|
||||
await tool.execute('call-1', {
|
||||
parent: 'folder-1',
|
||||
page: 2,
|
||||
pageSize: 10,
|
||||
type: 'folder',
|
||||
})
|
||||
|
||||
expect(assetService.listChildren).toHaveBeenCalledWith({
|
||||
assetId: 'folder-1',
|
||||
assetType: 'folder',
|
||||
sort: 'createdAt',
|
||||
order: 'desc',
|
||||
first: 10,
|
||||
after: expect.any(String),
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,6 +1,9 @@
|
||||
import { Type } from 'typebox'
|
||||
import { type AgentTool } from '@earendil-works/pi-agent-core'
|
||||
import { executeAgentToolWorkflow } from './utils'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { encodeCursor } from '@shumai/core/src/pagination'
|
||||
import { type User } from '@shumai/db'
|
||||
|
||||
const listAssetsSchema = Type.Object({
|
||||
parent: Type.String({
|
||||
@@ -19,9 +22,8 @@ const listAssetsSchema = Type.Object({
|
||||
}),
|
||||
),
|
||||
type: Type.Optional(
|
||||
Type.String({
|
||||
Type.Union([Type.Literal('file'), Type.Literal('folder'), Type.Literal('all')], {
|
||||
description: "Filter assets by type: 'file', 'folder', or 'all'. Default is 'all'.",
|
||||
enum: ['file', 'folder', 'all'],
|
||||
default: 'all',
|
||||
}),
|
||||
),
|
||||
@@ -34,15 +36,41 @@ export function createListAssetsTool(userId: string): AgentTool<typeof listAsset
|
||||
description: 'List the assets (files and folders) inside a parent folder with pagination.',
|
||||
parameters: listAssetsSchema,
|
||||
execute: async (_toolCallId, params) => {
|
||||
const result = await executeAgentToolWorkflow({
|
||||
toolName: 'list_assets',
|
||||
args: params,
|
||||
userId,
|
||||
assetId: params.parent,
|
||||
await authzService.hasPermission({
|
||||
user: { id: userId } as User,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: params.parent,
|
||||
})
|
||||
|
||||
const page = params.page || 1
|
||||
const pageSize = params.pageSize || 20
|
||||
const type = params.type || 'all'
|
||||
|
||||
const result = await assetService.listChildren({
|
||||
assetId: params.parent,
|
||||
assetType: type,
|
||||
sort: 'createdAt',
|
||||
order: 'desc',
|
||||
first: pageSize,
|
||||
after: page > 1 ? encodeCursor((page - 1) * pageSize) : undefined,
|
||||
})
|
||||
|
||||
const assets = result.data.map((a) => ({
|
||||
id: a.id,
|
||||
name: a.name,
|
||||
type: a.type,
|
||||
size: Number(a.sizeByte),
|
||||
}))
|
||||
|
||||
const output = {
|
||||
assets,
|
||||
pageInfo: result.pageInfo,
|
||||
}
|
||||
|
||||
return {
|
||||
content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
|
||||
details: result,
|
||||
content: [{ type: 'text', text: JSON.stringify(output, null, 2) }],
|
||||
details: output,
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
@@ -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')))
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
import { prisma } from '@shumai/db'
|
||||
import { workflowService } from '@shumai/workflow-core'
|
||||
import { WorkflowTaskType, WorkflowTaskStatus } from '@shumai/db'
|
||||
|
||||
export async function executeAgentToolWorkflow(params: {
|
||||
toolName: string
|
||||
args: Record<string, unknown>
|
||||
userId: string
|
||||
assetId: string
|
||||
}): Promise<unknown> {
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
type: WorkflowTaskType.agent_tool_call,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
assetId: params.assetId,
|
||||
payload: {
|
||||
projectId: 'none',
|
||||
agentToolCall: {
|
||||
toolName: params.toolName,
|
||||
args: params.args,
|
||||
userId: params.userId,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const completedTask = await workflowService.executeWait(task)
|
||||
if (completedTask.status === WorkflowTaskStatus.failed) {
|
||||
const output = completedTask.output as Record<string, unknown> | null
|
||||
const errorMsg = (output?.error as string) || 'Workflow task failed'
|
||||
throw new Error(errorMsg)
|
||||
}
|
||||
|
||||
return completedTask.output
|
||||
}
|
||||
@@ -64,6 +64,7 @@ describe('Agent Autofill Workflow', () => {
|
||||
mockActivities.createCommentActivity.mockResolvedValue({ id: 'comment-placeholder-id' })
|
||||
mockActivities.getAssetActivity.mockResolvedValue({
|
||||
id: 'a1',
|
||||
projectId: 'p1',
|
||||
storageKey: { key: 'asset-key' },
|
||||
project: { id: 'p1', teamId: 't1' },
|
||||
mediaType: 'image/png',
|
||||
@@ -117,6 +118,9 @@ describe('Agent Autofill Workflow', () => {
|
||||
status: 'processing',
|
||||
})
|
||||
|
||||
// Verify asset fetched
|
||||
expect(mockActivities.getAssetActivity).toHaveBeenCalledWith('a1')
|
||||
|
||||
// Verify placeholder comment created
|
||||
expect(mockActivities.createCommentActivity).toHaveBeenCalledWith({
|
||||
assetId: 'a1',
|
||||
@@ -143,6 +147,8 @@ describe('Agent Autofill Workflow', () => {
|
||||
// Verify AI autofill called with mapped fields
|
||||
expect(mockActivities.autofillAiActivity).toHaveBeenCalledWith({
|
||||
teamId: 't1',
|
||||
assetId: 'a1',
|
||||
projectId: 'p1',
|
||||
images: ['/tmp/test-dir/1.webp'],
|
||||
fields: [
|
||||
{
|
||||
|
||||
@@ -135,6 +135,8 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
|
||||
const aiResult = await executeActivity(agentWorkerQueue, autofillAiActivity, {
|
||||
teamId,
|
||||
images: generatedFiles,
|
||||
assetId: asset.id,
|
||||
projectId: asset.projectId ?? undefined,
|
||||
fields: fields.map(
|
||||
(f: { key: string; config: Record<string, unknown>; description?: string | null }) => ({
|
||||
id: f.key,
|
||||
|
||||
@@ -1,171 +0,0 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { AgentChatPromptBuilder } from './agent-chat-prompt-builder'
|
||||
|
||||
describe('AgentChatPromptBuilder', () => {
|
||||
it('should build prompt with baseline configurations', () => {
|
||||
const builder = new AgentChatPromptBuilder('a1')
|
||||
const result = builder.build()
|
||||
|
||||
expect(result).toContain('The user is discussing an asset with ID: a1.')
|
||||
})
|
||||
|
||||
it('should build prompt with path context', () => {
|
||||
const builder = new AgentChatPromptBuilder('a1').withPathContext('folder/sub/file.png')
|
||||
const result = builder.build()
|
||||
|
||||
expect(result).toContain('Asset Path Context:\nfolder/sub/file.png')
|
||||
})
|
||||
|
||||
it('should build prompt with image asset details', () => {
|
||||
const builder = new AgentChatPromptBuilder('a1').withAssetDetails(
|
||||
'test.png',
|
||||
'image/png',
|
||||
undefined,
|
||||
undefined,
|
||||
'image',
|
||||
)
|
||||
const result = builder.build()
|
||||
|
||||
expect(result).toContain('File Name: test.png')
|
||||
expect(result).toContain('File Type: image')
|
||||
expect(result).toContain("call the 'analyze_image' tool")
|
||||
expect(result).not.toContain("call the 'screenshot' tool")
|
||||
})
|
||||
|
||||
it('should build prompt with video asset details and duration', () => {
|
||||
const builder = new AgentChatPromptBuilder('a1').withAssetDetails(
|
||||
'movie.mp4',
|
||||
'video/mp4',
|
||||
12.34,
|
||||
undefined,
|
||||
'video',
|
||||
)
|
||||
const result = builder.build()
|
||||
|
||||
expect(result).toContain('File Name: movie.mp4')
|
||||
expect(result).toContain('File Type: video')
|
||||
expect(result).toContain('Video Length: 12.34 seconds')
|
||||
expect(result).toContain("call the 'screenshot' tool")
|
||||
expect(result).not.toContain("call the 'analyze_image' tool")
|
||||
})
|
||||
|
||||
it('should build prompt with PDF asset details and total pages', () => {
|
||||
const builder = new AgentChatPromptBuilder('a1').withAssetDetails(
|
||||
'doc.pdf',
|
||||
'application/pdf',
|
||||
undefined,
|
||||
15,
|
||||
'pdf',
|
||||
)
|
||||
const result = builder.build()
|
||||
|
||||
expect(result).toContain('File Name: doc.pdf')
|
||||
expect(result).toContain('File Type: pdf')
|
||||
expect(result).toContain('Total Pages: 15')
|
||||
expect(result).toContain("call the 'read_pdf_pages' tool")
|
||||
expect(result).toContain('Maximum 20 pages allowed per call.')
|
||||
expect(result).not.toContain("call the 'screenshot' tool")
|
||||
expect(result).not.toContain("call the 'analyze_image' tool")
|
||||
})
|
||||
|
||||
it('should build prompt with comment page for PDF asset', () => {
|
||||
const builder = new AgentChatPromptBuilder('a1')
|
||||
.withAssetDetails('doc.pdf', 'application/pdf', undefined, 10, 'pdf')
|
||||
.withCommentTimestamp(3)
|
||||
const result = builder.build()
|
||||
|
||||
expect(result).toContain('Comment Page: 3')
|
||||
})
|
||||
|
||||
it('should build prompt for PDF continuation mode with comment page', () => {
|
||||
const builder = new AgentChatPromptBuilder('a1')
|
||||
.withContinuation(true)
|
||||
.withAssetDetails('doc.pdf', 'application/pdf', undefined, 10, 'pdf')
|
||||
.withCommentTimestamp(4)
|
||||
const result = builder.build()
|
||||
|
||||
expect(result).toContain('Comment Page: 4')
|
||||
expect(result).not.toContain('Comment Timestamp:')
|
||||
})
|
||||
|
||||
it('should build prompt with comment timestamp', () => {
|
||||
const builder = new AgentChatPromptBuilder('a1').withCommentTimestamp(5.5)
|
||||
const result = builder.build()
|
||||
|
||||
expect(result).toContain('Comment Timestamp: 5.50 seconds')
|
||||
})
|
||||
|
||||
it('should build prompt with all fields combined', () => {
|
||||
const builder = new AgentChatPromptBuilder('a1')
|
||||
.withPathContext('src/main.ts')
|
||||
.withAssetDetails('movie.mp4', 'video/mp4', 12.34, undefined, 'video')
|
||||
.withCommentTimestamp(8.2)
|
||||
const result = builder.build()
|
||||
|
||||
expect(result).toContain('The user is discussing an asset with ID: a1.')
|
||||
expect(result).toContain('File Name: movie.mp4')
|
||||
expect(result).toContain('File Type: video')
|
||||
expect(result).toContain('Video Length: 12.34 seconds')
|
||||
expect(result).toContain('Comment Timestamp: 8.20 seconds')
|
||||
expect(result).toContain('Asset Path Context:\nsrc/main.ts')
|
||||
expect(result).toContain("call the 'screenshot' tool")
|
||||
})
|
||||
|
||||
it('should build prompt with attached files and referenced assets', () => {
|
||||
const builder = new AgentChatPromptBuilder('a1')
|
||||
.withAttachedFiles(['- file1.txt', '- file2.png'])
|
||||
.withReferencedAssets(['- folder1', '- file3.mp4'])
|
||||
const result = builder.build()
|
||||
|
||||
expect(result).toContain('[Context: Attached Files & Referenced Assets]')
|
||||
expect(result).toContain('Attached Files:\n- file1.txt\n- file2.png')
|
||||
expect(result).toContain('Referenced Workspace Assets:\n- folder1\n- file3.mp4')
|
||||
})
|
||||
|
||||
it('should build prompt for continuation mode returning only turn-specific modifications', () => {
|
||||
const builder = new AgentChatPromptBuilder('a1')
|
||||
.withContinuation(true)
|
||||
.withAssetDetails('movie.mp4', 'video/mp4', 12.34)
|
||||
.withPathContext('src/main.ts')
|
||||
.withCommentTimestamp(8.2)
|
||||
.withAttachedFiles(['- file1.txt'])
|
||||
.withReferencedAssets(['- folder1'])
|
||||
const result = builder.build()
|
||||
|
||||
expect(result).not.toContain('The user is discussing an asset with ID:')
|
||||
expect(result).not.toContain('File Name: movie.mp4')
|
||||
expect(result).not.toContain('Asset Path Context:')
|
||||
expect(result).toContain('Comment Timestamp: 8.20 seconds')
|
||||
expect(result).toContain('[Context: New Attached Files & Referenced Assets]')
|
||||
expect(result).toContain('Attached Files:\n- file1.txt')
|
||||
expect(result).toContain('Referenced Workspace Assets:\n- folder1')
|
||||
})
|
||||
|
||||
it('should include location change context block in continuation mode when asset has changed', () => {
|
||||
const builder = new AgentChatPromptBuilder('a2')
|
||||
.withContinuation(true)
|
||||
.withAssetChanged(true)
|
||||
.withAssetDetails('new-folder', 'folder', undefined, undefined, 'folder')
|
||||
.withPathContext('projects/my-proj/new-folder')
|
||||
const result = builder.build()
|
||||
|
||||
expect(result).toContain('[Context: User Navigated to a New Location]')
|
||||
expect(result).toContain('New Location Asset ID: a2')
|
||||
expect(result).toContain('File Name: new-folder')
|
||||
expect(result).toContain('Asset Path Context:\nprojects/my-proj/new-folder')
|
||||
})
|
||||
|
||||
it('should build prompt with user info when provided and not continuation', () => {
|
||||
const builder = new AgentChatPromptBuilder('a1').withUserInfo('Alice', 'owner')
|
||||
const result = builder.build()
|
||||
|
||||
expect(result).toContain('User Info:\nName: Alice\nRole: owner')
|
||||
})
|
||||
|
||||
it('should build prompt with download_asset tool instruction', () => {
|
||||
const builder = new AgentChatPromptBuilder('a1')
|
||||
const result = builder.build()
|
||||
|
||||
expect(result).toContain("call the 'download_asset' tool with assetId.")
|
||||
})
|
||||
})
|
||||
@@ -1,185 +0,0 @@
|
||||
export function getSimpleMediaType(proxyType?: string | null): 'image' | 'video' | 'pdf' | 'other' {
|
||||
if (proxyType === 'image') return 'image'
|
||||
if (proxyType === 'video') return 'video'
|
||||
if (proxyType === 'pdf') return 'pdf'
|
||||
return 'other'
|
||||
}
|
||||
|
||||
export class AgentChatPromptBuilder {
|
||||
private assetId: string
|
||||
private assetName?: string
|
||||
private mediaType?: string
|
||||
private proxyType?: string
|
||||
private videoDuration?: number
|
||||
private totalPages?: number
|
||||
private commentTimestamp?: number
|
||||
private pathContext?: string
|
||||
private attachedFiles: string[] = []
|
||||
private referencedAssets: string[] = []
|
||||
private userInfo?: { name: string; role: string }
|
||||
|
||||
private isContinuation = false
|
||||
private hasAssetChanged = false
|
||||
|
||||
constructor(assetId: string) {
|
||||
this.assetId = assetId
|
||||
}
|
||||
|
||||
withUserInfo(name?: string, role?: string): this {
|
||||
if (name) {
|
||||
this.userInfo = { name, role: role || 'user' }
|
||||
}
|
||||
return this
|
||||
}
|
||||
|
||||
withContinuation(isContinuation: boolean): this {
|
||||
this.isContinuation = isContinuation
|
||||
return this
|
||||
}
|
||||
|
||||
withAssetChanged(hasAssetChanged?: boolean): this {
|
||||
this.hasAssetChanged = !!hasAssetChanged
|
||||
return this
|
||||
}
|
||||
|
||||
withAttachedFiles(files?: string[]): this {
|
||||
if (files) {
|
||||
this.attachedFiles = files
|
||||
}
|
||||
return this
|
||||
}
|
||||
|
||||
withReferencedAssets(assets?: string[]): this {
|
||||
if (assets) {
|
||||
this.referencedAssets = assets
|
||||
}
|
||||
return this
|
||||
}
|
||||
|
||||
withPathContext(pathContext?: string): this {
|
||||
this.pathContext = pathContext
|
||||
return this
|
||||
}
|
||||
|
||||
withAssetDetails(
|
||||
name: string,
|
||||
mediaType: string | null,
|
||||
duration?: number,
|
||||
totalPages?: number,
|
||||
proxyType?: string | null,
|
||||
): this {
|
||||
this.assetName = name
|
||||
this.mediaType = mediaType || undefined
|
||||
this.proxyType = proxyType || undefined
|
||||
this.videoDuration = duration
|
||||
this.totalPages = totalPages
|
||||
return this
|
||||
}
|
||||
|
||||
withCommentTimestamp(second?: number | null): this {
|
||||
if (second !== undefined && second !== null) {
|
||||
this.commentTimestamp = second
|
||||
}
|
||||
return this
|
||||
}
|
||||
|
||||
build(): string {
|
||||
const effectiveType = this.proxyType
|
||||
|
||||
if (this.isContinuation) {
|
||||
let instruction = ''
|
||||
if (this.hasAssetChanged) {
|
||||
instruction += `[Context: User Navigated to a New Location]\nNew Location Asset ID: ${this.assetId}`
|
||||
if (this.assetName) {
|
||||
instruction += `\nFile Name: ${this.assetName}`
|
||||
}
|
||||
if (effectiveType) {
|
||||
const type = getSimpleMediaType(effectiveType)
|
||||
instruction += `\nFile Type: ${type}`
|
||||
if (type === 'video' && this.videoDuration !== undefined) {
|
||||
instruction += `\nVideo Length: ${this.videoDuration.toFixed(2)} seconds`
|
||||
} else if (type === 'pdf' && this.totalPages !== undefined) {
|
||||
instruction += `\nTotal Pages: ${this.totalPages}`
|
||||
}
|
||||
}
|
||||
if (this.pathContext) {
|
||||
instruction += `\n\nAsset Path Context:\n${this.pathContext}`
|
||||
}
|
||||
}
|
||||
if (this.commentTimestamp !== undefined) {
|
||||
const type = getSimpleMediaType(effectiveType)
|
||||
if (instruction) instruction += '\n\n'
|
||||
if (type === 'pdf') {
|
||||
instruction += `Comment Page: ${Math.round(this.commentTimestamp)}`
|
||||
} else {
|
||||
instruction += `Comment Timestamp: ${this.commentTimestamp.toFixed(2)} seconds`
|
||||
}
|
||||
}
|
||||
if (this.attachedFiles.length > 0 || this.referencedAssets.length > 0) {
|
||||
if (instruction) instruction += '\n\n'
|
||||
instruction += `[Context: New Attached Files & Referenced Assets]`
|
||||
if (this.attachedFiles.length > 0) {
|
||||
instruction += `\nAttached Files:\n${this.attachedFiles.join('\n')}`
|
||||
}
|
||||
if (this.referencedAssets.length > 0) {
|
||||
instruction += `\nReferenced Workspace Assets:\n${this.referencedAssets.join('\n')}`
|
||||
}
|
||||
}
|
||||
return instruction.trim()
|
||||
}
|
||||
|
||||
let instruction = `The user is discussing an asset with ID: ${this.assetId}.`
|
||||
if (this.assetName) {
|
||||
instruction += `\nFile Name: ${this.assetName}`
|
||||
}
|
||||
if (effectiveType) {
|
||||
const type = getSimpleMediaType(effectiveType)
|
||||
instruction += `\nFile Type: ${type}`
|
||||
if (type === 'video' && this.videoDuration !== undefined) {
|
||||
instruction += `\nVideo Length: ${this.videoDuration.toFixed(2)} seconds`
|
||||
} else if (type === 'pdf' && this.totalPages !== undefined) {
|
||||
instruction += `\nTotal Pages: ${this.totalPages}`
|
||||
}
|
||||
}
|
||||
if (this.commentTimestamp !== undefined) {
|
||||
const type = getSimpleMediaType(effectiveType)
|
||||
if (type === 'pdf') {
|
||||
instruction += `\nComment Page: ${Math.round(this.commentTimestamp)}`
|
||||
} else {
|
||||
instruction += `\nComment Timestamp: ${this.commentTimestamp.toFixed(2)} seconds`
|
||||
}
|
||||
}
|
||||
if (this.pathContext) {
|
||||
instruction += `\n\nAsset Path Context:\n${this.pathContext}`
|
||||
}
|
||||
|
||||
if (this.attachedFiles.length > 0 || this.referencedAssets.length > 0) {
|
||||
instruction += `\n\n[Context: Attached Files & Referenced Assets]`
|
||||
if (this.attachedFiles.length > 0) {
|
||||
instruction += `\nAttached Files:\n${this.attachedFiles.join('\n')}`
|
||||
}
|
||||
if (this.referencedAssets.length > 0) {
|
||||
instruction += `\nReferenced Workspace Assets:\n${this.referencedAssets.join('\n')}`
|
||||
}
|
||||
}
|
||||
|
||||
if (effectiveType) {
|
||||
const type = getSimpleMediaType(effectiveType)
|
||||
if (type === 'image') {
|
||||
instruction += `\n\nIf you need to view the image data, call the 'analyze_image' tool with assetId "${this.assetId}".`
|
||||
} else if (type === 'video') {
|
||||
instruction += `\n\nIf you need to view visual frames or take screenshots of the video, call the 'screenshot' tool. You must specify the 'start' (seconds), 'end' (seconds), and 'count' (number of screenshots) parameters.`
|
||||
} else if (type === 'pdf') {
|
||||
instruction += `\n\nIf you need to view pages of the PDF document, call the 'read_pdf_pages' tool. You must specify the 'start' (page number) and 'end' (page number) parameters. Maximum 20 pages allowed per call.`
|
||||
}
|
||||
}
|
||||
|
||||
instruction += `\n\nIf you need a local file on disk to run bash commands or scripts (e.g. processing or combining assets), call the 'download_asset' tool with assetId.`
|
||||
|
||||
if (this.userInfo) {
|
||||
instruction += `\n\nUser Info:\nName: ${this.userInfo.name}\nRole: ${this.userInfo.role}`
|
||||
}
|
||||
|
||||
return instruction
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,6 @@ import { agentChat } from './agent-chat'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import * as workflowUtils from '@shumai/workflow-core'
|
||||
import { AgentChatPromptBuilder } from './agent-chat-prompt-builder'
|
||||
|
||||
vi.mock('@shumai/workflow-core', async () => {
|
||||
const actual = await vi.importActual('@shumai/workflow-core')
|
||||
@@ -43,6 +42,9 @@ describe('Agent Chat Workflow', () => {
|
||||
updateCommentActivity: Object.assign(vi.fn(), { _activityName: 'updateCommentActivity' }),
|
||||
updateTaskUsageActivity: Object.assign(vi.fn(), { _activityName: 'updateTaskUsageActivity' }),
|
||||
deleteCommentActivity: Object.assign(vi.fn(), { _activityName: 'deleteCommentActivity' }),
|
||||
getAssetPathHierarchyActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getAssetPathHierarchyActivity',
|
||||
}),
|
||||
getAssetPathContextActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getAssetPathContextActivity',
|
||||
}),
|
||||
@@ -70,13 +72,21 @@ describe('Agent Chat Workflow', () => {
|
||||
})
|
||||
mockActivities.getCommentActivity.mockResolvedValue({
|
||||
id: 'c1',
|
||||
creatorId: 'user-c1',
|
||||
message: 'hello agent',
|
||||
replyToId: null,
|
||||
attachments: [],
|
||||
})
|
||||
mockActivities.initializeAgentSessionActivity.mockResolvedValue('session-123')
|
||||
mockActivities.getAgentChatContextActivity.mockResolvedValue({ agent: { id: 'b1' } })
|
||||
mockActivities.getAssetPathContextActivity.mockResolvedValue('Path: folder/subfolder/file.png')
|
||||
mockActivities.getAssetPathHierarchyActivity.mockResolvedValue({
|
||||
path: 'folder/subfolder/test-file.png',
|
||||
ancestors: [
|
||||
{ id: 'f1', name: 'folder' },
|
||||
{ id: 'f2', name: 'subfolder' },
|
||||
],
|
||||
})
|
||||
mockActivities.getAssetPathContextActivity.mockResolvedValue('folder/subfolder/test-file.png')
|
||||
mockActivities.agentChatActivity.mockResolvedValue({
|
||||
text: 'Hello user, how can I help you?',
|
||||
sessionId: 'session-123',
|
||||
@@ -118,6 +128,14 @@ describe('Agent Chat Workflow', () => {
|
||||
// Verify comment context fetched
|
||||
expect(mockActivities.getCommentActivity).toHaveBeenCalledWith('c1')
|
||||
|
||||
// Verify agent context fetched with the project context forwarded
|
||||
expect(mockActivities.getAgentChatContextActivity).toHaveBeenCalledWith({
|
||||
teamId: 't1',
|
||||
agentId: 'b1',
|
||||
userId: undefined,
|
||||
projectId: 'p1',
|
||||
})
|
||||
|
||||
// Verify placeholder comment created
|
||||
expect(mockActivities.createCommentActivity).toHaveBeenCalledWith({
|
||||
assetId: 'a1',
|
||||
@@ -135,21 +153,31 @@ describe('Agent Chat Workflow', () => {
|
||||
userId: undefined,
|
||||
})
|
||||
|
||||
// Verify agent instruction composition
|
||||
const expectedInstruction1 = new AgentChatPromptBuilder('a1')
|
||||
.withPathContext('Path: folder/subfolder/file.png')
|
||||
.withAssetDetails('test-file.png', 'image/png', undefined, undefined, 'image')
|
||||
.withCommentTimestamp(null)
|
||||
.build()
|
||||
|
||||
// Verify agent chat called with structured messageContext
|
||||
expect(mockActivities.agentChatActivity).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
teamId: 't1',
|
||||
agentId: 'b1',
|
||||
message: 'hello agent',
|
||||
agentsInstruction: expectedInstruction1,
|
||||
sessionId: 'session-123',
|
||||
folderId: 'parent-folder-id',
|
||||
assetId: 'a1',
|
||||
messageContext: expect.objectContaining({
|
||||
user: { id: 'user-c1', name: 'Test User', role: 'owner' },
|
||||
currentAsset: expect.objectContaining({
|
||||
id: 'a1',
|
||||
name: 'test-file.png',
|
||||
type: 'file',
|
||||
mediaType: 'image',
|
||||
mimeType: 'image/png',
|
||||
parentId: 'parent-folder-id',
|
||||
path: 'folder/subfolder/test-file.png',
|
||||
ancestors: [
|
||||
{ id: 'f1', name: 'folder' },
|
||||
{ id: 'f2', name: 'subfolder' },
|
||||
],
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
)
|
||||
|
||||
@@ -201,17 +229,13 @@ describe('Agent Chat Workflow', () => {
|
||||
await agentChat(task)
|
||||
|
||||
expect(mockActivities.initializeAgentSessionActivity).not.toHaveBeenCalled()
|
||||
const expectedInstruction2 = new AgentChatPromptBuilder('a1')
|
||||
.withContinuation(true)
|
||||
.withPathContext('Path: folder/subfolder/file.png')
|
||||
.withAssetDetails('test-file.png', 'image/png', undefined)
|
||||
.withCommentTimestamp(null)
|
||||
.build()
|
||||
|
||||
expect(mockActivities.agentChatActivity).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
sessionId: 'existing-session-456',
|
||||
agentsInstruction: expectedInstruction2,
|
||||
messageContext: expect.objectContaining({
|
||||
currentAsset: expect.objectContaining({ id: 'a1', name: 'test-file.png' }),
|
||||
}),
|
||||
}),
|
||||
)
|
||||
|
||||
@@ -263,16 +287,9 @@ describe('Agent Chat Workflow', () => {
|
||||
|
||||
await agentChat(task)
|
||||
|
||||
const expectedInstruction4 = new AgentChatPromptBuilder('a1')
|
||||
.withPathContext('Path: folder/subfolder/file.png')
|
||||
.withAssetDetails('test-file.png', 'image/png', undefined, undefined, 'image')
|
||||
.withCommentTimestamp(null)
|
||||
.build()
|
||||
|
||||
expect(mockActivities.agentChatActivity).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
imageUrls: ['attachments/image1.png', 'attachments/image2.jpg'],
|
||||
agentsInstruction: expectedInstruction4,
|
||||
}),
|
||||
)
|
||||
})
|
||||
@@ -305,15 +322,13 @@ describe('Agent Chat Workflow', () => {
|
||||
|
||||
await agentChat(task)
|
||||
|
||||
const expectedInstruction5 = new AgentChatPromptBuilder('a1')
|
||||
.withPathContext('Path: folder/subfolder/file.png')
|
||||
.withAssetDetails('test-asset', 'video/mp4', 10)
|
||||
.withCommentTimestamp(null)
|
||||
.build()
|
||||
|
||||
expect(mockActivities.agentChatActivity).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
agentsInstruction: expectedInstruction5,
|
||||
messageContext: expect.objectContaining({
|
||||
currentAsset: expect.objectContaining({
|
||||
durationSeconds: 10,
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
)
|
||||
})
|
||||
@@ -381,6 +396,7 @@ describe('Agent Chat Workflow', () => {
|
||||
name: 'attachment.png',
|
||||
type: 'file',
|
||||
mediaType: 'image/png',
|
||||
media: { proxyType: 'image' },
|
||||
projectId: 'p1',
|
||||
}
|
||||
}
|
||||
@@ -390,6 +406,7 @@ describe('Agent Chat Workflow', () => {
|
||||
name: 'ref-folder',
|
||||
type: 'folder',
|
||||
mediaType: null,
|
||||
media: null,
|
||||
projectId: 'p1',
|
||||
}
|
||||
}
|
||||
@@ -398,6 +415,7 @@ describe('Agent Chat Workflow', () => {
|
||||
name: 'test-file.png',
|
||||
type: 'file',
|
||||
mediaType: 'image/png',
|
||||
media: { proxyType: 'image' },
|
||||
projectId: 'p1',
|
||||
project: { teamId: 't1' },
|
||||
}
|
||||
@@ -433,20 +451,7 @@ describe('Agent Chat Workflow', () => {
|
||||
expect(mockActivities.createCommentActivity).not.toHaveBeenCalled()
|
||||
expect(mockActivities.updateCommentActivity).not.toHaveBeenCalled()
|
||||
|
||||
// Verify prompt builder is populated and workflow runs agentChatActivity with context instruction
|
||||
const expectedInstruction = new AgentChatPromptBuilder('a1')
|
||||
.withContinuation(true)
|
||||
.withPathContext('folder/subfolder/file.png')
|
||||
.withAssetDetails('test-file.png', 'image/png', undefined)
|
||||
.withCommentTimestamp(undefined)
|
||||
.withAttachedFiles([
|
||||
'- Name: attachment.png (ID: file-attachment-1, Type: file, Media Type: image/png, Project ID: p1, Path: attachment.png)',
|
||||
])
|
||||
.withReferencedAssets([
|
||||
'- Name: ref-folder (ID: referenced-asset-1, Type: folder, Media Type: unknown, Project ID: p1, Path: ref-folder)',
|
||||
])
|
||||
.build()
|
||||
|
||||
// Verify messageContext is populated with attachedFiles and referencedAssets
|
||||
expect(mockActivities.agentChatActivity).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
teamId: 't1',
|
||||
@@ -455,15 +460,32 @@ describe('Agent Chat Workflow', () => {
|
||||
imageUrls: [],
|
||||
projectId: 'p1',
|
||||
folderId: '',
|
||||
agentsInstruction: expectedInstruction,
|
||||
sessionId: 'session-direct-123',
|
||||
userId: undefined,
|
||||
userCommentId: undefined,
|
||||
context: { agent: { id: 'b1' } },
|
||||
attachedAssets: [
|
||||
{ id: 'file-attachment-1', name: 'attachment.png', type: 'file' },
|
||||
{ id: 'referenced-asset-1', name: 'ref-folder', type: 'folder' },
|
||||
],
|
||||
messageContext: expect.objectContaining({
|
||||
attachedFiles: [
|
||||
{
|
||||
id: 'file-attachment-1',
|
||||
name: 'attachment.png',
|
||||
type: 'file',
|
||||
mediaType: 'image',
|
||||
mimeType: 'image/png',
|
||||
path: 'attachment.png',
|
||||
},
|
||||
],
|
||||
referencedAssets: [
|
||||
{
|
||||
id: 'referenced-asset-1',
|
||||
name: 'ref-folder',
|
||||
type: 'folder',
|
||||
mediaType: undefined,
|
||||
mimeType: undefined,
|
||||
path: 'ref-folder',
|
||||
},
|
||||
],
|
||||
}),
|
||||
}),
|
||||
)
|
||||
})
|
||||
@@ -502,19 +524,18 @@ describe('Agent Chat Workflow', () => {
|
||||
|
||||
await agentChat(task)
|
||||
|
||||
const expectedInstruction = new AgentChatPromptBuilder('v2-latest')
|
||||
.withContinuation(true)
|
||||
.withPathContext('Path: folder/subfolder/file.png')
|
||||
.withAssetDetails('latest-video.mp4', 'video/mp4', 42, undefined, 'video')
|
||||
.build()
|
||||
|
||||
expect(mockActivities.agentChatActivity).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
teamId: 't1',
|
||||
agentId: 'b1',
|
||||
message: 'Explain this version stack video',
|
||||
agentsInstruction: expectedInstruction,
|
||||
sessionId: 'session-vs-123',
|
||||
messageContext: expect.objectContaining({
|
||||
currentAsset: expect.objectContaining({
|
||||
id: 'v2-latest',
|
||||
durationSeconds: 42,
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
)
|
||||
})
|
||||
@@ -547,7 +568,170 @@ describe('Agent Chat Workflow', () => {
|
||||
|
||||
expect(mockActivities.agentChatActivity).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
agentsInstruction: expect.stringContaining('User Info:\nName: Test User\nRole: owner'),
|
||||
messageContext: expect.objectContaining({
|
||||
user: { id: 'user-alice', name: 'Test User', role: 'owner' },
|
||||
}),
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('should populate comment attachments into structured messageContext.attachedFiles', async () => {
|
||||
mockActivities.getCommentActivity.mockResolvedValue({
|
||||
id: 'c1',
|
||||
creatorId: 'user-c1',
|
||||
message: 'check these attachments',
|
||||
replyToId: null,
|
||||
attachments: [
|
||||
{
|
||||
asset: {
|
||||
id: 'att-doc-1',
|
||||
name: 'brief.pdf',
|
||||
type: 'file',
|
||||
mediaType: 'application/pdf',
|
||||
media: { proxyType: 'pdf' },
|
||||
storageKey: { key: 'brief.pdf' },
|
||||
},
|
||||
},
|
||||
{
|
||||
asset: {
|
||||
id: 'att-img-1',
|
||||
name: 'mockup.png',
|
||||
type: 'file',
|
||||
mediaType: 'image/png',
|
||||
media: { proxyType: 'image' },
|
||||
storageKey: { key: 'mockup.png' },
|
||||
},
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
mockActivities.getAssetPathContextActivity.mockImplementation(async (id: string) => {
|
||||
if (id === 'att-doc-1') return 'Docs/brief.pdf'
|
||||
if (id === 'att-img-1') return 'Designs/mockup.png'
|
||||
return 'folder/subfolder/file.png'
|
||||
})
|
||||
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
type: 'chat',
|
||||
status: 'pending',
|
||||
assetId: 'a1',
|
||||
payload: {
|
||||
projectId: 'p1',
|
||||
agent: { userCommentId: 'c1', agentId: 'b1' },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
await agentChat(task)
|
||||
|
||||
expect(mockActivities.agentChatActivity).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
imageUrls: ['mockup.png'],
|
||||
messageContext: expect.objectContaining({
|
||||
attachedFiles: [
|
||||
{
|
||||
id: 'att-doc-1',
|
||||
name: 'brief.pdf',
|
||||
type: 'file',
|
||||
mediaType: 'pdf',
|
||||
mimeType: 'application/pdf',
|
||||
path: 'Docs/brief.pdf',
|
||||
},
|
||||
{
|
||||
id: 'att-img-1',
|
||||
name: 'mockup.png',
|
||||
type: 'file',
|
||||
mediaType: 'image',
|
||||
mimeType: 'image/png',
|
||||
path: 'Designs/mockup.png',
|
||||
},
|
||||
],
|
||||
}),
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('should set totalFrames for video assets and totalPages for pdf assets in currentAsset context', async () => {
|
||||
mockActivities.getAssetActivity.mockImplementation(async (id: string) => {
|
||||
if (id === 'video-asset-1') {
|
||||
return {
|
||||
id: 'video-asset-1',
|
||||
project: { teamId: 't1' },
|
||||
type: 'file',
|
||||
name: 'clip.mp4',
|
||||
mediaType: 'video/mp4',
|
||||
media: { proxyType: 'video', duration: 9, frames: 268 },
|
||||
parentId: 'f1',
|
||||
}
|
||||
}
|
||||
if (id === 'pdf-asset-1') {
|
||||
return {
|
||||
id: 'pdf-asset-1',
|
||||
project: { teamId: 't1' },
|
||||
type: 'file',
|
||||
name: 'doc.pdf',
|
||||
mediaType: 'application/pdf',
|
||||
media: { proxyType: 'pdf', frames: 15, duration: 0 },
|
||||
parentId: 'f1',
|
||||
}
|
||||
}
|
||||
return null
|
||||
})
|
||||
|
||||
// Test Video asset
|
||||
const videoTask = await prisma.workflowTask.create({
|
||||
data: {
|
||||
type: 'chat',
|
||||
status: 'pending',
|
||||
assetId: 'video-asset-1',
|
||||
payload: {
|
||||
projectId: 'p1',
|
||||
agent: { prompt: 'Analyze video', agentId: 'b1', sessionId: 'session-video-1' },
|
||||
},
|
||||
},
|
||||
})
|
||||
await agentChat(videoTask)
|
||||
|
||||
expect(mockActivities.agentChatActivity).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
messageContext: expect.objectContaining({
|
||||
currentAsset: expect.objectContaining({
|
||||
id: 'video-asset-1',
|
||||
mediaType: 'video',
|
||||
durationSeconds: 9,
|
||||
totalFrames: 268,
|
||||
totalPages: undefined,
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
)
|
||||
|
||||
// Test PDF asset
|
||||
const pdfTask = await prisma.workflowTask.create({
|
||||
data: {
|
||||
type: 'chat',
|
||||
status: 'pending',
|
||||
assetId: 'pdf-asset-1',
|
||||
payload: {
|
||||
projectId: 'p1',
|
||||
agent: { prompt: 'Analyze pdf', agentId: 'b1', sessionId: 'session-pdf-1' },
|
||||
},
|
||||
},
|
||||
})
|
||||
await agentChat(pdfTask)
|
||||
|
||||
expect(mockActivities.agentChatActivity).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
messageContext: expect.objectContaining({
|
||||
currentAsset: expect.objectContaining({
|
||||
id: 'pdf-asset-1',
|
||||
mediaType: 'pdf',
|
||||
totalPages: 15,
|
||||
totalFrames: undefined,
|
||||
durationSeconds: undefined,
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
import { ApplicationFailure } from '@temporalio/workflow'
|
||||
import type { WorkflowTask } from '@shumai/db'
|
||||
import { executeActivity, getActivities, TaskQueueAgent } from '@shumai/workflow-core'
|
||||
import { AgentChatPromptBuilder } from './agent-chat-prompt-builder'
|
||||
import type {
|
||||
ShumaiMessageContext,
|
||||
ShumaiAssetContext,
|
||||
ShumaiAttachedFileContext,
|
||||
ShumaiMediaPosition,
|
||||
} from '@shumai/dtos'
|
||||
import { getProxyType } from '@shumai/core/src/utils/mime'
|
||||
|
||||
export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
const {
|
||||
@@ -15,6 +21,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
updateTaskUsageActivity,
|
||||
getAgentWorkerQueueActivity,
|
||||
initializeAgentSessionActivity,
|
||||
getAssetPathHierarchyActivity,
|
||||
getAssetPathContextActivity,
|
||||
generateSessionNameActivity,
|
||||
getUserTeamInfoActivity,
|
||||
@@ -47,19 +54,30 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
|
||||
// 1. Get User Comment
|
||||
const userCommentId = payload.agent?.userCommentId
|
||||
let userComment: Awaited<ReturnType<typeof getCommentActivity>> | null = null
|
||||
let prompt = ''
|
||||
let attachmentImageUrls: string[] = []
|
||||
let commentTimestamp: number | undefined
|
||||
let commentAnnotation = false
|
||||
let commentCreatorId: string | undefined
|
||||
|
||||
if (userCommentId) {
|
||||
const userComment = await executeActivity(agentWorkerQueue, getCommentActivity, userCommentId)
|
||||
userComment = await executeActivity(agentWorkerQueue, getCommentActivity, userCommentId)
|
||||
if (!userComment) {
|
||||
throw ApplicationFailure.create({ message: 'User comment not found', nonRetryable: true })
|
||||
}
|
||||
prompt = userComment.message || ''
|
||||
commentCreatorId = userComment.creatorId || undefined
|
||||
if (userComment.second !== null && userComment.second !== undefined) {
|
||||
commentTimestamp = userComment.second
|
||||
}
|
||||
if (
|
||||
userComment.annotation &&
|
||||
Array.isArray(userComment.annotation) &&
|
||||
userComment.annotation.length > 0
|
||||
) {
|
||||
commentAnnotation = true
|
||||
}
|
||||
|
||||
// 2. Create Placeholder Comment
|
||||
const placeholder = await executeActivity(agentWorkerQueue, createCommentActivity, {
|
||||
@@ -71,7 +89,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
})
|
||||
placeholderCommentId = placeholder.id
|
||||
|
||||
// 5. Prepare Images (Attachments only)
|
||||
// Prepare Images (Attachments only)
|
||||
if (userComment.attachments) {
|
||||
for (const att of userComment.attachments) {
|
||||
const attProxyType = (att.asset?.media as PrismaJson.MediaInfo | null)?.proxyType
|
||||
@@ -114,45 +132,108 @@ 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(
|
||||
const pathHierarchy = await executeActivity(
|
||||
agentWorkerQueue,
|
||||
getAssetPathContextActivity,
|
||||
getAssetPathHierarchyActivity,
|
||||
task.assetId,
|
||||
)
|
||||
const assetPath = pathHierarchy?.path || ''
|
||||
const ancestors = pathHierarchy?.ancestors || []
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const mediaInfo = asset.media as any
|
||||
const duration = mediaInfo?.duration
|
||||
const totalPages = mediaInfo?.frames || mediaInfo?.metadata?.totalFrames
|
||||
const proxyType =
|
||||
(asset.media as PrismaJson.MediaInfo | null)?.proxyType ||
|
||||
getProxyType(asset.mediaType, asset.name) ||
|
||||
undefined
|
||||
const duration =
|
||||
(proxyType === 'video' || proxyType === 'audio') && typeof mediaInfo?.duration === 'number'
|
||||
? mediaInfo.duration
|
||||
: undefined
|
||||
const totalPages =
|
||||
proxyType === 'pdf' ? mediaInfo?.frames || mediaInfo?.metadata?.totalFrames : undefined
|
||||
const totalFrames =
|
||||
proxyType === 'video' ? mediaInfo?.frames || mediaInfo?.metadata?.totalFrames : undefined
|
||||
|
||||
// Resolve Attached Files Details
|
||||
const attachedFileDetailsList: string[] = []
|
||||
const attachedFiles: ShumaiAttachedFileContext[] = []
|
||||
const attachedAssets: Array<{ id: string; name: string; type: string }> = []
|
||||
if (payload.agent?.attachedFiles) {
|
||||
if (userCommentId && userComment?.attachments) {
|
||||
for (const att of userComment.attachments) {
|
||||
if (att.asset) {
|
||||
const filePath = await executeActivity(
|
||||
agentWorkerQueue,
|
||||
getAssetPathContextActivity,
|
||||
att.asset.id,
|
||||
)
|
||||
const attProxyType =
|
||||
(att.asset.media as PrismaJson.MediaInfo | null)?.proxyType ||
|
||||
getProxyType(att.asset.mediaType, att.asset.name) ||
|
||||
undefined
|
||||
attachedFiles.push({
|
||||
id: att.asset.id,
|
||||
name: att.asset.name,
|
||||
type: att.asset.type,
|
||||
mediaType: attProxyType as ShumaiAttachedFileContext['mediaType'],
|
||||
mimeType: att.asset.mediaType || undefined,
|
||||
path: filePath || undefined,
|
||||
})
|
||||
attachedAssets.push({ id: att.asset.id, name: att.asset.name, type: att.asset.type })
|
||||
}
|
||||
}
|
||||
} else if (payload.agent?.attachedFiles) {
|
||||
for (const fileId of payload.agent.attachedFiles) {
|
||||
const file = await executeActivity(agentWorkerQueue, getAssetActivity, fileId)
|
||||
if (file) {
|
||||
const path = await executeActivity(agentWorkerQueue, getAssetPathContextActivity, fileId)
|
||||
attachedFileDetailsList.push(
|
||||
`- Name: ${file.name} (ID: ${file.id}, Type: ${file.type}, Media Type: ${file.mediaType || 'unknown'}, Project ID: ${file.projectId || 'unknown'}, Path: ${path})`,
|
||||
const filePath = await executeActivity(
|
||||
agentWorkerQueue,
|
||||
getAssetPathContextActivity,
|
||||
fileId,
|
||||
)
|
||||
const fileProxyType =
|
||||
(file.media as PrismaJson.MediaInfo | null)?.proxyType ||
|
||||
getProxyType(file.mediaType, file.name) ||
|
||||
undefined
|
||||
attachedFiles.push({
|
||||
id: file.id,
|
||||
name: file.name,
|
||||
type: file.type,
|
||||
mediaType: fileProxyType as ShumaiAttachedFileContext['mediaType'],
|
||||
mimeType: file.mediaType || undefined,
|
||||
path: filePath || undefined,
|
||||
})
|
||||
attachedAssets.push({ id: file.id, name: file.name, type: file.type })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Resolve Referenced Workspace Assets Details
|
||||
const referencedAssetDetailsList: string[] = []
|
||||
const referencedAssets: ShumaiAttachedFileContext[] = []
|
||||
if (payload.agent?.assetIds) {
|
||||
for (const assetId of payload.agent.assetIds) {
|
||||
const referencedAsset = await executeActivity(agentWorkerQueue, getAssetActivity, assetId)
|
||||
if (referencedAsset) {
|
||||
const path = await executeActivity(agentWorkerQueue, getAssetPathContextActivity, assetId)
|
||||
referencedAssetDetailsList.push(
|
||||
`- Name: ${referencedAsset.name} (ID: ${referencedAsset.id}, Type: ${referencedAsset.type}, Media Type: ${referencedAsset.mediaType || 'unknown'}, Project ID: ${referencedAsset.projectId || 'unknown'}, Path: ${path})`,
|
||||
const filePath = await executeActivity(
|
||||
agentWorkerQueue,
|
||||
getAssetPathContextActivity,
|
||||
assetId,
|
||||
)
|
||||
const refProxyType =
|
||||
(referencedAsset.media as PrismaJson.MediaInfo | null)?.proxyType ||
|
||||
getProxyType(referencedAsset.mediaType, referencedAsset.name) ||
|
||||
undefined
|
||||
referencedAssets.push({
|
||||
id: referencedAsset.id,
|
||||
name: referencedAsset.name,
|
||||
type: referencedAsset.type,
|
||||
mediaType: refProxyType as ShumaiAttachedFileContext['mediaType'],
|
||||
mimeType: referencedAsset.mediaType || undefined,
|
||||
path: filePath || undefined,
|
||||
})
|
||||
attachedAssets.push({
|
||||
id: referencedAsset.id,
|
||||
name: referencedAsset.name,
|
||||
@@ -162,29 +243,53 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
// Resolve User Info
|
||||
const targetUserId = userCommentId ? commentCreatorId : payload.agent?.userId
|
||||
let userInfo: { name: string; role: string } | null = null
|
||||
if (!userCommentId && isNewChat && payload.agent?.userId) {
|
||||
if (targetUserId) {
|
||||
userInfo = await executeActivity(agentWorkerQueue, getUserTeamInfoActivity, {
|
||||
userId: payload.agent.userId,
|
||||
userId: targetUserId,
|
||||
teamId,
|
||||
})
|
||||
}
|
||||
|
||||
const proxyType = (asset.media as PrismaJson.MediaInfo | null)?.proxyType
|
||||
const promptBuilder = new AgentChatPromptBuilder(asset.id)
|
||||
.withContinuation(!isNewChat)
|
||||
.withAssetChanged(payload.agent?.hasAssetChanged)
|
||||
.withPathContext(pathContext)
|
||||
.withAssetDetails(asset.name, asset.mediaType, duration, totalPages, proxyType)
|
||||
.withCommentTimestamp(commentTimestamp)
|
||||
.withAttachedFiles(attachedFileDetailsList)
|
||||
.withReferencedAssets(referencedAssetDetailsList)
|
||||
|
||||
if (userInfo) {
|
||||
promptBuilder.withUserInfo(userInfo.name, userInfo.role)
|
||||
// Build position
|
||||
let mediaPosition: ShumaiMediaPosition | undefined
|
||||
if (commentTimestamp !== undefined && commentTimestamp !== null) {
|
||||
if (proxyType === 'pdf') {
|
||||
mediaPosition = { type: 'page', page: Math.round(commentTimestamp) }
|
||||
} else {
|
||||
mediaPosition = { type: 'time', seconds: commentTimestamp }
|
||||
}
|
||||
}
|
||||
|
||||
const instruction = promptBuilder.build()
|
||||
// Build Current Asset Context
|
||||
const currentAssetContext: ShumaiAssetContext = {
|
||||
id: asset.id,
|
||||
name: asset.name,
|
||||
type: asset.type,
|
||||
mediaType: proxyType as ShumaiAssetContext['mediaType'],
|
||||
mimeType: asset.mediaType || undefined,
|
||||
parentId: asset.parentId || undefined,
|
||||
path: assetPath || undefined,
|
||||
durationSeconds: duration !== undefined ? duration : undefined,
|
||||
totalFrames: totalFrames !== undefined ? totalFrames : undefined,
|
||||
totalPages: totalPages !== undefined ? totalPages : undefined,
|
||||
navigated: payload.agent?.hasAssetChanged === true ? true : undefined,
|
||||
ancestors: ancestors.length > 0 ? ancestors : undefined,
|
||||
}
|
||||
|
||||
// Build structured ShumaiMessageContext
|
||||
const messageContext: ShumaiMessageContext = {
|
||||
...(userInfo
|
||||
? { user: { id: targetUserId!, name: userInfo.name, role: userInfo.role } }
|
||||
: {}),
|
||||
currentAsset: currentAssetContext,
|
||||
...(mediaPosition ? { position: mediaPosition } : {}),
|
||||
...(commentAnnotation ? { annotation: true } : {}),
|
||||
...(attachedFiles.length > 0 ? { attachedFiles } : {}),
|
||||
...(referencedAssets.length > 0 ? { referencedAssets } : {}),
|
||||
}
|
||||
|
||||
// 6. Call AI Chat
|
||||
let folderId = ''
|
||||
@@ -202,11 +307,12 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
imageUrls: attachmentImageUrls,
|
||||
projectId: payload.projectId,
|
||||
folderId,
|
||||
agentsInstruction: instruction,
|
||||
assetId: asset.id,
|
||||
sessionId,
|
||||
userId: payload.agent?.userId,
|
||||
userCommentId: userCommentId || undefined,
|
||||
context,
|
||||
messageContext,
|
||||
attachedAssets,
|
||||
})
|
||||
|
||||
|
||||
@@ -1,140 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { agentToolCall } from './agent-tool-call'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import * as workflowUtils from '@shumai/workflow-core'
|
||||
|
||||
vi.mock('@shumai/workflow-core', async () => {
|
||||
const actual = await vi.importActual('@shumai/workflow-core')
|
||||
return {
|
||||
...actual,
|
||||
getActivities: vi.fn(),
|
||||
executeActivity: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
describe('Agent Tool Call Workflow', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mockActivities holds mock functions cast to expected types
|
||||
let mockActivities: any
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
|
||||
mockActivities = {
|
||||
updateTaskStatusActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateTaskStatusActivity',
|
||||
}),
|
||||
executeAgentToolActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'executeAgentToolActivity',
|
||||
}),
|
||||
getAgentWorkerQueueActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getAgentWorkerQueueActivity',
|
||||
}),
|
||||
}
|
||||
|
||||
mockActivities.getAgentWorkerQueueActivity.mockResolvedValue('agent_queue')
|
||||
mockActivities.updateTaskStatusActivity.mockResolvedValue({})
|
||||
mockActivities.executeAgentToolActivity.mockResolvedValue({ success: true, count: 42 })
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mockActivities contains vi.fn mock functions which are cast to expected activity proxy types
|
||||
vi.mocked(workflowUtils.getActivities).mockReturnValue(mockActivities as any)
|
||||
vi.mocked(workflowUtils.executeActivity).mockImplementation(async (_queue, act, ...args) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- act is one of the mocked activities
|
||||
return (act as any)(...args)
|
||||
})
|
||||
})
|
||||
|
||||
it('should run agent tool call workflow successfully', async () => {
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
type: 'agent_tool_call',
|
||||
status: 'pending',
|
||||
assetId: 'a1',
|
||||
payload: {
|
||||
projectId: 'p1',
|
||||
agentToolCall: {
|
||||
toolName: 'list_assets',
|
||||
args: { parent: 'folder-123' },
|
||||
userId: 'user-456',
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
await agentToolCall(task)
|
||||
|
||||
// Verify queue discovery
|
||||
expect(mockActivities.getAgentWorkerQueueActivity).toHaveBeenCalled()
|
||||
|
||||
// Verify task processing status
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
||||
taskId: task.id,
|
||||
status: 'processing',
|
||||
})
|
||||
|
||||
// Verify tool execution
|
||||
expect(mockActivities.executeAgentToolActivity).toHaveBeenCalledWith({
|
||||
taskId: task.id,
|
||||
toolName: 'list_assets',
|
||||
args: { parent: 'folder-123' },
|
||||
userId: 'user-456',
|
||||
})
|
||||
|
||||
// Verify task completed status with output
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
||||
taskId: task.id,
|
||||
status: 'completed',
|
||||
output: { success: true, count: 42 },
|
||||
})
|
||||
})
|
||||
|
||||
it('should throw if payload or agentToolCall is missing', async () => {
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
type: 'agent_tool_call',
|
||||
status: 'pending',
|
||||
assetId: 'a1',
|
||||
},
|
||||
})
|
||||
|
||||
await expect(agentToolCall(task)).rejects.toThrow('Task payload or agentToolCall is missing')
|
||||
|
||||
// Verify status updated to failed
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
||||
taskId: task.id,
|
||||
status: 'failed',
|
||||
output: { error: 'Task payload or agentToolCall is missing' },
|
||||
})
|
||||
})
|
||||
|
||||
it('should handle tool execution failures by updating task to failed and throwing', async () => {
|
||||
mockActivities.executeAgentToolActivity.mockRejectedValue(new Error('Authz failure'))
|
||||
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
type: 'agent_tool_call',
|
||||
status: 'pending',
|
||||
assetId: 'a1',
|
||||
payload: {
|
||||
projectId: 'p1',
|
||||
agentToolCall: {
|
||||
toolName: 'create_folder',
|
||||
args: { parent: 'folder-123', name: 'new-folder' },
|
||||
userId: 'user-456',
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
await expect(agentToolCall(task)).rejects.toThrow('Authz failure')
|
||||
|
||||
// Verify task status failed
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
||||
taskId: task.id,
|
||||
status: 'failed',
|
||||
output: { error: 'Authz failure' },
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,60 +0,0 @@
|
||||
import { ApplicationFailure } from '@temporalio/workflow'
|
||||
import type { WorkflowTask } from '@shumai/db'
|
||||
import { getActivities, executeActivity, TaskQueueAgent } from '@shumai/workflow-core'
|
||||
|
||||
export async function agentToolCall(task: WorkflowTask): Promise<void> {
|
||||
const { updateTaskStatusActivity, executeAgentToolActivity, getAgentWorkerQueueActivity } =
|
||||
getActivities()
|
||||
|
||||
let agentWorkerQueue = ''
|
||||
|
||||
try {
|
||||
// 0. Discover queue
|
||||
agentWorkerQueue = await executeActivity(TaskQueueAgent, getAgentWorkerQueueActivity)
|
||||
|
||||
// Update status to processing
|
||||
await executeActivity(agentWorkerQueue, updateTaskStatusActivity, {
|
||||
taskId: task.id,
|
||||
status: 'processing',
|
||||
})
|
||||
|
||||
const payload = task.payload
|
||||
if (!payload || !payload.agentToolCall) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'Task payload or agentToolCall is missing',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const { toolName, args, userId } = payload.agentToolCall
|
||||
|
||||
// Execute the agent activity on specific queue
|
||||
const result = await executeActivity(agentWorkerQueue, executeAgentToolActivity, {
|
||||
taskId: task.id,
|
||||
toolName,
|
||||
args,
|
||||
userId,
|
||||
})
|
||||
|
||||
// Update status to completed with output
|
||||
await executeActivity(agentWorkerQueue, updateTaskStatusActivity, {
|
||||
taskId: task.id,
|
||||
status: 'completed',
|
||||
output: result,
|
||||
})
|
||||
} catch (err) {
|
||||
console.error(`AgentToolCall failed for task ${task.id}:`, err)
|
||||
|
||||
// Update status to failed
|
||||
if (agentWorkerQueue) {
|
||||
await executeActivity(agentWorkerQueue, updateTaskStatusActivity, {
|
||||
taskId: task.id,
|
||||
status: 'failed',
|
||||
output: { error: err instanceof Error ? err.message : String(err) },
|
||||
})
|
||||
}
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
export const agentToolCallWorkflow = agentToolCall
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/api",
|
||||
"version": "0.3.7",
|
||||
"version": "0.4.1",
|
||||
"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 () => {
|
||||
@@ -310,4 +350,59 @@ describe('folder api', () => {
|
||||
beforeIndex: 'index-1',
|
||||
})
|
||||
})
|
||||
|
||||
it('GET /folders/:folderId/agentsmd', async () => {
|
||||
vi.spyOn(assetService, 'getAgentsMd').mockResolvedValue('# Folder Guidelines')
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
|
||||
const res = await app.request('/folders/test-id/agentsmd')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.content).toBe('# Folder Guidelines')
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: 'test-id',
|
||||
})
|
||||
expect(assetService.getAgentsMd).toHaveBeenCalledWith('test-id')
|
||||
})
|
||||
|
||||
it('PATCH /folders/:folderId/agentsmd', async () => {
|
||||
vi.spyOn(assetService, 'updateAgentsMd').mockResolvedValue({ content: '# Updated Guidelines' })
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
|
||||
const res = await app.request('/folders/test-id/agentsmd', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ content: '# Updated Guidelines' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.content).toBe('# Updated Guidelines')
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Asset,
|
||||
id: 'test-id',
|
||||
})
|
||||
expect(assetService.updateAgentsMd).toHaveBeenCalledWith('test-id', '# Updated Guidelines')
|
||||
})
|
||||
|
||||
it('PATCH /folders/:folderId/agentsmd rejects oversized content', async () => {
|
||||
const mockUpdate = vi.spyOn(assetService, 'updateAgentsMd').mockResolvedValue({ content: '' })
|
||||
const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
|
||||
const res = await app.request('/folders/test-id/agentsmd', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ content: 'x'.repeat(100_001) }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
expect(mockUpdate).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
updateFolderRequestSchema,
|
||||
deleteFoldersRequestSchema,
|
||||
restoreFoldersRequestSchema,
|
||||
updateAgentsMdRequestSchema,
|
||||
} from '@shumai/dtos'
|
||||
import { listChildrenRequestSchema, updateAssetOrderRequestSchema, AuditAction } from '@shumai/dtos'
|
||||
import { searchRequestSchema } from '@shumai/dtos'
|
||||
@@ -119,12 +120,8 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
})
|
||||
|
||||
const resp = await assetService.listChildren({
|
||||
...req,
|
||||
assetId: folderId,
|
||||
assetType: req.assetType,
|
||||
projectId: req.projectId,
|
||||
showDeleted: req.showDeleted,
|
||||
sort: req.sort,
|
||||
order: req.order,
|
||||
})
|
||||
return c.json(resp)
|
||||
})
|
||||
@@ -189,5 +186,48 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
const result = await searchService.search(folderId, req)
|
||||
return c.json(result)
|
||||
})
|
||||
.get('/folders/:folderId/agentsmd', async (c) => {
|
||||
const folderId = c.req.param('folderId')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: folderId,
|
||||
})
|
||||
|
||||
const content = await assetService.getAgentsMd(folderId)
|
||||
return c.json({ content })
|
||||
})
|
||||
.patch(
|
||||
'/folders/:folderId/agentsmd',
|
||||
zValidator('json', updateAgentsMdRequestSchema),
|
||||
async (c) => {
|
||||
const folderId = c.req.param('folderId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Asset,
|
||||
id: folderId,
|
||||
})
|
||||
|
||||
const res = await assetService.updateAgentsMd(folderId, req.content)
|
||||
|
||||
const ctx = await assetService.getAssetContext(folderId)
|
||||
await auditLogService.logAction({
|
||||
action: AuditAction.folder_update,
|
||||
teamId: ctx.teamId,
|
||||
userId: user.id,
|
||||
projectId: ctx.projectId,
|
||||
itemId: folderId,
|
||||
})
|
||||
|
||||
return c.json(res)
|
||||
},
|
||||
)
|
||||
|
||||
export default route
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -4,7 +4,7 @@ import { zValidator } from '@hono/zod-validator'
|
||||
import { shareService } from '@shumai/core/src/share/share'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { watermarkService } from '@shumai/core/src/watermark/watermark'
|
||||
import { paginationParamsSchema } from '@shumai/dtos'
|
||||
import { paginationParamsSchema, assetTypeFilterSchema } from '@shumai/dtos'
|
||||
import { z } from 'zod'
|
||||
import { metadataService } from '@shumai/core/src/metadata/metadata'
|
||||
import { FieldInfo } from '@shumai/dtos'
|
||||
@@ -117,7 +117,7 @@ export function handlePublicShareError(c: Context, err: unknown) {
|
||||
}
|
||||
|
||||
const sharedChildrenRequestSchema = paginationParamsSchema.extend({
|
||||
assetType: z.string().optional(),
|
||||
assetType: assetTypeFilterSchema.optional().default('file'),
|
||||
})
|
||||
|
||||
const route = app
|
||||
|
||||
@@ -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' },
|
||||
|
||||
@@ -32,12 +32,14 @@ vi.mock('./middleware/auth', () => ({
|
||||
describe('versionStack api', () => {
|
||||
let mockCreateVersionStack: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockChangeStackFileVersion: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockRemoveVersionFromStack: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockGetAsset: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockGetStackVersions: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
|
||||
beforeEach(() => {
|
||||
mockCreateVersionStack = vi.spyOn(versionStackService, 'createVersionStack')
|
||||
mockChangeStackFileVersion = vi.spyOn(versionStackService, 'changeStackFileVersion')
|
||||
mockRemoveVersionFromStack = vi.spyOn(versionStackService, 'removeVersionFromStack')
|
||||
mockGetAsset = vi.spyOn(assetService, 'getAsset')
|
||||
mockGetStackVersions = vi.spyOn(assetService, 'getStackVersions')
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
|
||||
@@ -146,4 +148,30 @@ describe('versionStack api', () => {
|
||||
expect(mockGetStackVersions).toHaveBeenCalledWith('stack1')
|
||||
})
|
||||
})
|
||||
|
||||
describe('DELETE /version_stacks/:stackId/versions/:versionId', () => {
|
||||
it('should remove version from stack and return 200', async () => {
|
||||
mockRemoveVersionFromStack.mockResolvedValue()
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', versionStackRoute)
|
||||
|
||||
const res = await app.request('/version_stacks/stack1/versions/v1', {
|
||||
method: 'DELETE',
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Asset,
|
||||
id: 'stack1',
|
||||
permission: Permission.Edit,
|
||||
}),
|
||||
)
|
||||
expect(mockRemoveVersionFromStack).toHaveBeenCalledWith({
|
||||
stackId: 'stack1',
|
||||
fileId: 'v1',
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -75,5 +75,24 @@ const route = app
|
||||
const versions = await assetService.getStackVersions(stackId)
|
||||
return c.json(versions)
|
||||
})
|
||||
.delete('/version_stacks/:stackId/versions/:versionId', async (c) => {
|
||||
const stackId = c.req.param('stackId')
|
||||
const versionId = c.req.param('versionId')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: stackId,
|
||||
})
|
||||
|
||||
await versionStackService.removeVersionFromStack({
|
||||
stackId,
|
||||
fileId: versionId,
|
||||
})
|
||||
|
||||
return new Response(null, { status: 200 })
|
||||
})
|
||||
|
||||
export default route
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shumai/core",
|
||||
"version": "0.3.7",
|
||||
"version": "0.4.1",
|
||||
"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']
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -16,35 +16,43 @@ import {
|
||||
UpdateAssetNameRequest,
|
||||
UpdateAssetOrderRequest,
|
||||
AssetUserInfo,
|
||||
ListRecentsRequest,
|
||||
} from '@shumai/dtos'
|
||||
import { type Asset, AssetStatus, AssetType, Prisma, type StorageKey } from '@shumai/db'
|
||||
import { HTTPException } from 'hono/http-exception'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import { PaginatedData, paginateQuery, PaginationParams } from '@shumai/core/src/pagination'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { dedupeSymlinksToTarget } from './symlink'
|
||||
import { watermarkService } from '@shumai/core/src/watermark/watermark'
|
||||
import { generateKeyBetween } from 'jittered-fractional-indexing'
|
||||
import { getAvatarUrl } from '@shumai/core/src/user/avatar'
|
||||
import { getAgentRequiredLevel, getRoleLevel } from '@shumai/core/src/agent/permissions'
|
||||
import { resolveEffectiveRole } from '@shumai/core/src/authz/authz'
|
||||
import { metadataService } from '@shumai/core/src/metadata/metadata'
|
||||
import { uploadService } from '@shumai/core/src/upload/upload'
|
||||
|
||||
type AssetWithIncludes = Prisma.AssetGetPayload<{
|
||||
include: {
|
||||
creator: true
|
||||
metadataValues: true
|
||||
storageKey: true
|
||||
target: {
|
||||
include: {
|
||||
creator: true
|
||||
metadataValues: true
|
||||
storageKey: true
|
||||
children: {
|
||||
include: { creator: true; metadataValues: true; storageKey: true }
|
||||
}
|
||||
}
|
||||
}
|
||||
children: {
|
||||
include: { creator: true; metadataValues: true; storageKey: true }
|
||||
}
|
||||
}
|
||||
export const assetInclude = {
|
||||
creator: true,
|
||||
metadataValues: true,
|
||||
storageKey: true,
|
||||
target: {
|
||||
include: {
|
||||
creator: true,
|
||||
metadataValues: true,
|
||||
storageKey: true,
|
||||
children: {
|
||||
include: { creator: true, metadataValues: true, storageKey: true },
|
||||
},
|
||||
},
|
||||
},
|
||||
children: {
|
||||
include: { creator: true, metadataValues: true, storageKey: true },
|
||||
},
|
||||
} as const
|
||||
|
||||
export type AssetWithIncludes = Prisma.AssetGetPayload<{
|
||||
include: typeof assetInclude
|
||||
}>
|
||||
|
||||
type CommentWithIncludes = Prisma.AssetCommentGetPayload<{
|
||||
@@ -160,6 +168,9 @@ export class AssetService {
|
||||
const count = await tx.asset.count({ where: { parentId: stack.id } })
|
||||
|
||||
if (count === 0) {
|
||||
await tx.asset.deleteMany({
|
||||
where: { targetId: stack.id, type: AssetType.symlink },
|
||||
})
|
||||
if (stack.parentId) {
|
||||
await tx.asset.update({
|
||||
where: { id: stack.parentId },
|
||||
@@ -174,9 +185,14 @@ export class AssetService {
|
||||
if (!lastChild) return
|
||||
if (!stack.parentId) throw new Error('Stack has no parent')
|
||||
|
||||
await tx.asset.updateMany({
|
||||
where: { targetId: stack.id, type: AssetType.symlink },
|
||||
data: { targetId: lastChild.id, name: lastChild.name },
|
||||
})
|
||||
|
||||
await tx.asset.update({
|
||||
where: { id: lastChild.id },
|
||||
data: { parentId: stack.parentId, sortIndex: null },
|
||||
data: { parentId: stack.parentId, sortIndex: stack.sortIndex },
|
||||
})
|
||||
await tx.asset.delete({ where: { id: stack.id } })
|
||||
}
|
||||
@@ -195,6 +211,12 @@ export class AssetService {
|
||||
return this.reparentFileToFile(tx, newParent, req.assetIds, req.creatorId)
|
||||
}
|
||||
|
||||
if (newParent.type === AssetType.version_stack) {
|
||||
if (req.assetIds.length !== 1) {
|
||||
throw new Error('Can only move one file at a time into a version stack')
|
||||
}
|
||||
}
|
||||
|
||||
const assetsToMove = await tx.asset.findMany({
|
||||
where: { id: { in: req.assetIds } },
|
||||
include: { project: { include: { team: true } } },
|
||||
@@ -206,6 +228,14 @@ export class AssetService {
|
||||
|
||||
if (assetsToMove.length === 0) return
|
||||
|
||||
if (newParent.type === AssetType.version_stack) {
|
||||
for (const a of assetsToMove) {
|
||||
if (a.type !== AssetType.file) {
|
||||
throw new Error(`Cannot move ${a.type} asset into a version stack`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let totalSize = 0
|
||||
const oldParentId = assetsToMove[0].parentId
|
||||
if (!oldParentId) {
|
||||
@@ -273,6 +303,14 @@ export class AssetService {
|
||||
firstSortIndex = newSortIndex
|
||||
}
|
||||
|
||||
if (newParent.type === AssetType.version_stack) {
|
||||
await dedupeSymlinksToTarget(tx, {
|
||||
targetIds: req.assetIds,
|
||||
newTargetId: newParent.id,
|
||||
name: '',
|
||||
})
|
||||
}
|
||||
|
||||
const oldParent = await tx.asset.findUnique({
|
||||
where: { id: oldParentId },
|
||||
})
|
||||
@@ -500,6 +538,10 @@ export class AssetService {
|
||||
assetIds: string[],
|
||||
creatorId?: string,
|
||||
) {
|
||||
if (destFile.type !== AssetType.file) {
|
||||
throw new Error('Destination asset must be a file')
|
||||
}
|
||||
|
||||
if (assetIds.length !== 1) {
|
||||
throw new Error('Can only reparent one file to another file')
|
||||
}
|
||||
@@ -515,6 +557,10 @@ export class AssetService {
|
||||
|
||||
if (!sourceAsset) throw new Error('Source asset not found')
|
||||
|
||||
if (sourceAsset.type !== AssetType.file) {
|
||||
throw new Error('Source asset must be a file to create a version stack')
|
||||
}
|
||||
|
||||
if (!sourceAsset.project || !sourceAsset.project.team) {
|
||||
throw new Error(`Asset ${sourceAsset.id} is not associated with a team`)
|
||||
}
|
||||
@@ -579,6 +625,12 @@ export class AssetService {
|
||||
},
|
||||
})
|
||||
|
||||
// Update existing symlinks pointing to destFile or sourceAsset
|
||||
await dedupeSymlinksToTarget(tx, {
|
||||
targetIds: [destFile.id, sourceAsset.id],
|
||||
newTargetId: stack.id,
|
||||
})
|
||||
|
||||
const oldParent = await tx.asset.findUnique({ where: { id: oldParentId } })
|
||||
if (oldParent) {
|
||||
await this.dissolveStackIfEmpty(tx, oldParent)
|
||||
@@ -586,9 +638,13 @@ export class AssetService {
|
||||
}
|
||||
|
||||
async listChildren(req: ListChildrenRequest): Promise<PaginatedData<AssetInfo[]>> {
|
||||
const typesToQuery: AssetType[] = [req.assetType as AssetType]
|
||||
if (req.assetType === AssetType.file) {
|
||||
typesToQuery.push(AssetType.version_stack)
|
||||
let typesToQuery: AssetType[]
|
||||
if (req.assetType === 'file') {
|
||||
typesToQuery = [AssetType.file, AssetType.version_stack]
|
||||
} else if (req.assetType === 'folder') {
|
||||
typesToQuery = [AssetType.folder]
|
||||
} else {
|
||||
typesToQuery = [AssetType.file, AssetType.folder, AssetType.version_stack]
|
||||
}
|
||||
|
||||
let where: Prisma.AssetWhereInput = {}
|
||||
@@ -604,10 +660,7 @@ export class AssetService {
|
||||
projectId: req.projectId,
|
||||
isDeleted: true,
|
||||
deletedAt: { gte: thirtyDaysAgo },
|
||||
OR: [
|
||||
{ type: { in: typesToQuery } },
|
||||
{ type: AssetType.symlink, target: { type: { in: typesToQuery } } },
|
||||
],
|
||||
type: { in: typesToQuery },
|
||||
}
|
||||
} else {
|
||||
if (!req.assetId) {
|
||||
@@ -626,7 +679,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 } } },
|
||||
],
|
||||
}
|
||||
}
|
||||
@@ -696,12 +749,17 @@ export class AssetService {
|
||||
return { data: infos, pageInfo }
|
||||
}
|
||||
|
||||
async createAsset(req: CreateAssetRequest): Promise<AssetInfo> {
|
||||
async createAsset(
|
||||
req: CreateAssetRequest,
|
||||
txClient?: Prisma.TransactionClient,
|
||||
): Promise<AssetInfo> {
|
||||
const db = txClient ?? this.prismaClient
|
||||
|
||||
let projectId = req.projectId
|
||||
let parent: Prisma.AssetGetPayload<{ include: { project: true } }> | null = null
|
||||
|
||||
if (req.parentId) {
|
||||
parent = await this.prismaClient.asset.findUnique({
|
||||
parent = await db.asset.findUnique({
|
||||
where: { id: req.parentId },
|
||||
include: { project: true },
|
||||
})
|
||||
@@ -713,7 +771,7 @@ export class AssetService {
|
||||
|
||||
let sortIndex: string | null = null
|
||||
if (parent) {
|
||||
const firstFile = await this.prismaClient.asset.findFirst({
|
||||
const firstFile = await db.asset.findFirst({
|
||||
where: { parentId: parent.id },
|
||||
orderBy: { sortIndex: 'asc' },
|
||||
})
|
||||
@@ -741,7 +799,7 @@ export class AssetService {
|
||||
if (req.contentType) data.mediaType = req.contentType
|
||||
if (req.creatorId) data.creator = { connect: { id: req.creatorId } }
|
||||
|
||||
const asset = await this.prismaClient.$transaction(async (tx) => {
|
||||
const executeInTx = async (tx: Prisma.TransactionClient) => {
|
||||
const createdAsset = await tx.asset.create({
|
||||
data,
|
||||
include: {
|
||||
@@ -778,12 +836,165 @@ export class AssetService {
|
||||
}
|
||||
|
||||
return createdAsset
|
||||
})
|
||||
}
|
||||
|
||||
const asset = txClient
|
||||
? await executeInTx(txClient)
|
||||
: await this.prismaClient.$transaction(executeInTx)
|
||||
|
||||
const infos = await this.toAssetInfos([asset])
|
||||
return infos[0]
|
||||
}
|
||||
|
||||
async createFile(params: {
|
||||
parentId: string
|
||||
name: string
|
||||
key: string
|
||||
sizeByte: number
|
||||
contentType: string
|
||||
creatorId: string
|
||||
metadata?: Record<string, unknown>
|
||||
}): Promise<AssetInfo> {
|
||||
const { parentId, name, key, sizeByte, contentType, creatorId, metadata } = params
|
||||
|
||||
const parentAsset = await this.prismaClient.asset.findUnique({
|
||||
where: { id: parentId },
|
||||
include: { project: true },
|
||||
})
|
||||
if (!parentAsset || !parentAsset.projectId || !parentAsset.project?.teamId) {
|
||||
throw new Error(`Parent folder ${parentId} is invalid or has no project associated`)
|
||||
}
|
||||
|
||||
if (metadata) {
|
||||
await metadataService.validateCreationContextMetadata(
|
||||
creatorId,
|
||||
parentAsset.projectId,
|
||||
metadata,
|
||||
)
|
||||
}
|
||||
|
||||
let newFileId = ''
|
||||
await this.prismaClient.$transaction(async (tx) => {
|
||||
const newFile = await this.createAsset(
|
||||
{
|
||||
name,
|
||||
type: 'file',
|
||||
parentId,
|
||||
key,
|
||||
sizeByte,
|
||||
contentType,
|
||||
creatorId,
|
||||
},
|
||||
tx,
|
||||
)
|
||||
newFileId = newFile.id
|
||||
|
||||
await this.updateAncestorsSize(tx, parentId, sizeByte)
|
||||
if (metadata) {
|
||||
const metadataUpdates = Object.entries(metadata)
|
||||
.filter(([, value]) => value !== null)
|
||||
.map(([k, v]) => ({ key: k, value: v }))
|
||||
if (metadataUpdates.length > 0) {
|
||||
await metadataService.updateAssetMetadataInTx(tx, newFile.id, metadataUpdates)
|
||||
}
|
||||
}
|
||||
await uploadService.triggerPostUploadWorkflows(
|
||||
tx,
|
||||
newFile.id,
|
||||
parentAsset.project!.teamId,
|
||||
parentAsset.projectId!,
|
||||
)
|
||||
})
|
||||
|
||||
return this.getAsset({ assetId: newFileId })
|
||||
}
|
||||
|
||||
async createVersion(params: {
|
||||
parentId: string
|
||||
name: string
|
||||
key: string
|
||||
sizeByte: number
|
||||
contentType: string
|
||||
creatorId: string
|
||||
metadata?: Record<string, unknown>
|
||||
}): Promise<AssetInfo> {
|
||||
const { parentId, name, key, sizeByte, contentType, creatorId, metadata } = params
|
||||
|
||||
const targetAsset = await this.prismaClient.asset.findUnique({
|
||||
where: { id: parentId },
|
||||
include: { project: true, parent: true },
|
||||
})
|
||||
if (!targetAsset || !targetAsset.projectId || !targetAsset.project?.teamId) {
|
||||
throw new Error(`Target file ${parentId} is invalid or has no project associated`)
|
||||
}
|
||||
|
||||
if (metadata) {
|
||||
await metadataService.validateCreationContextMetadata(
|
||||
creatorId,
|
||||
targetAsset.projectId,
|
||||
metadata,
|
||||
)
|
||||
}
|
||||
|
||||
let targetFolderId: string
|
||||
let reparentTargetId: string
|
||||
|
||||
if (targetAsset.type === AssetType.version_stack) {
|
||||
targetFolderId = targetAsset.parentId!
|
||||
reparentTargetId = targetAsset.id
|
||||
} else if (targetAsset.parent?.type === AssetType.version_stack) {
|
||||
targetFolderId = targetAsset.parent.parentId!
|
||||
reparentTargetId = targetAsset.parentId!
|
||||
} else {
|
||||
targetFolderId = targetAsset.parentId!
|
||||
reparentTargetId = targetAsset.id
|
||||
}
|
||||
|
||||
let newFileId = ''
|
||||
await this.prismaClient.$transaction(async (tx) => {
|
||||
const newFile = await this.createAsset(
|
||||
{
|
||||
name,
|
||||
type: 'file',
|
||||
parentId: targetFolderId,
|
||||
key,
|
||||
sizeByte,
|
||||
contentType,
|
||||
creatorId,
|
||||
},
|
||||
tx,
|
||||
)
|
||||
newFileId = newFile.id
|
||||
|
||||
await this.reparentAssets(
|
||||
{
|
||||
assetIds: [newFile.id],
|
||||
newParentId: reparentTargetId,
|
||||
creatorId,
|
||||
},
|
||||
tx,
|
||||
)
|
||||
|
||||
if (metadata) {
|
||||
const metadataUpdates = Object.entries(metadata)
|
||||
.filter(([, value]) => value !== null)
|
||||
.map(([k, v]) => ({ key: k, value: v }))
|
||||
if (metadataUpdates.length > 0) {
|
||||
await metadataService.updateAssetMetadataInTx(tx, newFile.id, metadataUpdates)
|
||||
}
|
||||
}
|
||||
|
||||
await uploadService.triggerPostUploadWorkflows(
|
||||
tx,
|
||||
newFile.id,
|
||||
targetAsset.project!.teamId,
|
||||
targetAsset.projectId!,
|
||||
)
|
||||
})
|
||||
|
||||
return this.getAsset({ assetId: newFileId })
|
||||
}
|
||||
|
||||
async findAsset(parentId: string, name: string): Promise<AssetInfo | null> {
|
||||
const asset = await this.prismaClient.asset.findFirst({
|
||||
where: { parentId, name },
|
||||
@@ -932,9 +1143,42 @@ export class AssetService {
|
||||
}
|
||||
|
||||
async updateAssetName(req: UpdateAssetNameRequest): Promise<AssetInfo> {
|
||||
const asset = await this.prismaClient.asset.update({
|
||||
const existing = await this.prismaClient.asset.findUnique({
|
||||
where: { id: req.id },
|
||||
include: { target: true },
|
||||
})
|
||||
if (!existing) throw new Error('Asset not found')
|
||||
|
||||
let targetType = existing.type
|
||||
let targetId = existing.id
|
||||
|
||||
if (existing.type === AssetType.symlink && existing.target) {
|
||||
targetType = existing.target.type
|
||||
targetId = existing.target.id
|
||||
}
|
||||
|
||||
if (targetType === AssetType.version_stack) {
|
||||
const latestChild = await this.prismaClient.asset.findFirst({
|
||||
where: { parentId: targetId, isDeleted: false },
|
||||
orderBy: { sortIndex: 'asc' },
|
||||
select: { id: true },
|
||||
})
|
||||
if (!latestChild) {
|
||||
throw new Error('No active version found in stack to rename')
|
||||
}
|
||||
await this.prismaClient.asset.update({
|
||||
where: { id: latestChild.id },
|
||||
data: { name: req.name },
|
||||
})
|
||||
} else {
|
||||
await this.prismaClient.asset.update({
|
||||
where: { id: req.id },
|
||||
data: { name: req.name },
|
||||
})
|
||||
}
|
||||
|
||||
const asset = await this.prismaClient.asset.findUnique({
|
||||
where: { id: req.id },
|
||||
data: { name: req.name },
|
||||
include: {
|
||||
creator: true,
|
||||
metadataValues: true,
|
||||
@@ -960,6 +1204,8 @@ export class AssetService {
|
||||
storageKey: true,
|
||||
},
|
||||
})
|
||||
if (!asset) throw new Error('Asset not found')
|
||||
|
||||
const infos = await this.toAssetInfos([asset as unknown as AssetWithIncludes])
|
||||
return infos[0]
|
||||
}
|
||||
@@ -1040,6 +1286,39 @@ export class AssetService {
|
||||
})
|
||||
}
|
||||
|
||||
const allDeletedIds = [a.id, ...descendantIds]
|
||||
const symlinks = await tx.asset.findMany({
|
||||
where: {
|
||||
targetId: { in: allDeletedIds },
|
||||
isDeleted: false,
|
||||
type: AssetType.symlink,
|
||||
},
|
||||
})
|
||||
|
||||
if (symlinks.length > 0) {
|
||||
await tx.asset.updateMany({
|
||||
where: { id: { in: symlinks.map((s) => s.id) } },
|
||||
data: {
|
||||
isDeleted: true,
|
||||
status: AssetStatus.trashed,
|
||||
deletedAt: new Date(),
|
||||
},
|
||||
})
|
||||
|
||||
const parentCounts = new Map<string, number>()
|
||||
for (const s of symlinks) {
|
||||
if (s.parentId) {
|
||||
parentCounts.set(s.parentId, (parentCounts.get(s.parentId) || 0) + 1)
|
||||
}
|
||||
}
|
||||
for (const [parentId, count] of parentCounts.entries()) {
|
||||
await tx.asset.update({
|
||||
where: { id: parentId },
|
||||
data: { fileCount: { decrement: count } },
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
await tx.asset.update({
|
||||
where: { id: a.id },
|
||||
data: {
|
||||
@@ -1063,9 +1342,16 @@ export class AssetService {
|
||||
UNION ALL
|
||||
SELECT a.id FROM assets a
|
||||
INNER JOIN descendant d ON a.parent_id = d.id
|
||||
),
|
||||
all_purging_targets AS (
|
||||
SELECT id FROM descendant
|
||||
),
|
||||
all_affected_symlinks AS (
|
||||
SELECT s.id FROM assets s
|
||||
WHERE s.type = 'symlink' AND s.target_id IN (SELECT id FROM all_purging_targets)
|
||||
)
|
||||
UPDATE assets SET status = 'pending_purge', updated_at = NOW()
|
||||
WHERE id IN (SELECT id FROM descendant);
|
||||
WHERE id IN (SELECT id FROM all_purging_targets) OR id IN (SELECT id FROM all_affected_symlinks);
|
||||
`
|
||||
}
|
||||
|
||||
@@ -1251,6 +1537,39 @@ export class AssetService {
|
||||
})
|
||||
}
|
||||
|
||||
const allRestoredIds = [a.id, ...descendantIds]
|
||||
const symlinks = await tx.asset.findMany({
|
||||
where: {
|
||||
targetId: { in: allRestoredIds },
|
||||
isDeleted: true,
|
||||
type: AssetType.symlink,
|
||||
},
|
||||
})
|
||||
|
||||
if (symlinks.length > 0) {
|
||||
await tx.asset.updateMany({
|
||||
where: { id: { in: symlinks.map((s) => s.id) } },
|
||||
data: {
|
||||
isDeleted: false,
|
||||
status: AssetStatus.processed,
|
||||
deletedAt: null,
|
||||
},
|
||||
})
|
||||
|
||||
const parentCounts = new Map<string, number>()
|
||||
for (const s of symlinks) {
|
||||
if (s.parentId) {
|
||||
parentCounts.set(s.parentId, (parentCounts.get(s.parentId) || 0) + 1)
|
||||
}
|
||||
}
|
||||
for (const [parentId, count] of parentCounts.entries()) {
|
||||
await tx.asset.update({
|
||||
where: { id: parentId },
|
||||
data: { fileCount: { increment: count } },
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
await tx.asset.update({
|
||||
where: { id: a.id },
|
||||
data: {
|
||||
@@ -1319,30 +1638,43 @@ export class AssetService {
|
||||
const mentionedAgentIds = new Set(botMentionMatches.map((match) => match[1]))
|
||||
const handledAgentIds = new Set<string>()
|
||||
|
||||
// Effective role for the project context (project override wins; project-
|
||||
// scoped members without project access resolve to null and are denied).
|
||||
const effectiveRole = a.project?.team
|
||||
? await resolveEffectiveRole(a.project.team.id, a.project.id, req.userId, tx)
|
||||
: null
|
||||
|
||||
const userLevel = getRoleLevel(effectiveRole)
|
||||
|
||||
if (parentComment && a.project) {
|
||||
const rootSessionId = parentComment.sessionId
|
||||
const isRootAgent = !!rootSessionId || parentComment.creator?.type === 'agent'
|
||||
const rootAgentId = parentComment.creatorId
|
||||
|
||||
if (isRootAgent && rootAgentId && mentionedAgentIds.has(rootAgentId)) {
|
||||
await tx.workflowTask.create({
|
||||
data: {
|
||||
assetId: a.id,
|
||||
type: 'chat',
|
||||
status: 'pending',
|
||||
teamId: a.project.team.id,
|
||||
projectId: a.project.id,
|
||||
payload: {
|
||||
const rootAgent = await tx.agent.findUnique({ where: { id: rootAgentId } })
|
||||
const requiredLevel = getAgentRequiredLevel(rootAgent?.permission)
|
||||
|
||||
if (userLevel >= requiredLevel) {
|
||||
await tx.workflowTask.create({
|
||||
data: {
|
||||
assetId: a.id,
|
||||
type: 'chat',
|
||||
status: 'pending',
|
||||
teamId: a.project.team.id,
|
||||
projectId: a.project.id,
|
||||
agent: {
|
||||
userCommentId: comment.id,
|
||||
agentId: rootAgentId,
|
||||
sessionId: rootSessionId || undefined,
|
||||
userId: req.userId,
|
||||
payload: {
|
||||
projectId: a.project.id,
|
||||
agent: {
|
||||
userCommentId: comment.id,
|
||||
agentId: rootAgentId,
|
||||
sessionId: rootSessionId || undefined,
|
||||
userId: req.userId,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
})
|
||||
}
|
||||
handledAgentIds.add(rootAgentId)
|
||||
}
|
||||
}
|
||||
@@ -1356,7 +1688,12 @@ export class AssetService {
|
||||
foundAgent = true
|
||||
} else {
|
||||
const agent = await tx.agent.findUnique({ where: { id: agentId } })
|
||||
if (agent) foundAgent = true
|
||||
if (agent) {
|
||||
const requiredLevel = getAgentRequiredLevel(agent.permission)
|
||||
if (userLevel >= requiredLevel) {
|
||||
foundAgent = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (foundAgent && a.project) {
|
||||
@@ -1545,7 +1882,7 @@ export class AssetService {
|
||||
return { data: infos, pageInfo }
|
||||
}
|
||||
|
||||
private async toAssetInfos(assets: AssetWithIncludes[]): Promise<AssetInfo[]> {
|
||||
async toAssetInfos(assets: AssetWithIncludes[]): Promise<AssetInfo[]> {
|
||||
const stackIds = new Set<string>()
|
||||
|
||||
for (const a of assets) {
|
||||
@@ -1592,6 +1929,15 @@ export class AssetService {
|
||||
}
|
||||
}
|
||||
|
||||
const agentMdRecords =
|
||||
assets.length > 0
|
||||
? await this.prismaClient.assetAgentMd.findMany({
|
||||
where: { assetId: { in: assets.map((a) => a.id) } },
|
||||
select: { assetId: true },
|
||||
})
|
||||
: []
|
||||
const hasAgentMdSet = new Set(agentMdRecords.map((r) => r.assetId))
|
||||
|
||||
const result: AssetInfo[] = []
|
||||
for (const a of assets) {
|
||||
let latestVersion:
|
||||
@@ -1620,6 +1966,7 @@ export class AssetService {
|
||||
id: v.id,
|
||||
name: v.name,
|
||||
previewUrl: preview?.thumbnailUrl || null,
|
||||
createdAt: v.createdAt.toISOString(),
|
||||
creator: v.creator
|
||||
? {
|
||||
id: v.creator.id,
|
||||
@@ -1735,9 +2082,12 @@ export class AssetService {
|
||||
result.push({
|
||||
id: a.id,
|
||||
name:
|
||||
a.type === AssetType.version_stack && (a.name === '' || !a.name)
|
||||
a.type === AssetType.version_stack ||
|
||||
(a.type === AssetType.symlink && a.target?.type === AssetType.version_stack)
|
||||
? latestVersion.name
|
||||
: a.name,
|
||||
: a.type === AssetType.symlink
|
||||
? a.name || latestVersion.name || a.target?.name || ''
|
||||
: a.name,
|
||||
sizeByte: Number(latestVersion.sizeByte),
|
||||
fileCount: latestVersion.fileCount,
|
||||
type: a.type,
|
||||
@@ -1753,6 +2103,7 @@ export class AssetService {
|
||||
creator,
|
||||
fieldValues,
|
||||
sortIndex: a.sortIndex,
|
||||
hasAgentsMd: hasAgentMdSet.has(a.id),
|
||||
media: media as unknown as AssetInfo['media'],
|
||||
versionStack,
|
||||
})
|
||||
@@ -1766,7 +2117,8 @@ export class AssetService {
|
||||
version: number
|
||||
name: string
|
||||
previewUrl: string | null
|
||||
creator: { id: string; name: string | null } | null
|
||||
createdAt: string
|
||||
creator: { id: string; name: string | null; image?: string | null } | null
|
||||
}>
|
||||
> {
|
||||
const versions = await this.prismaClient.asset.findMany({
|
||||
@@ -1787,6 +2139,7 @@ export class AssetService {
|
||||
version: versions.length - i,
|
||||
name: v.name,
|
||||
previewUrl: preview?.thumbnailUrl || null,
|
||||
createdAt: v.createdAt.toISOString(),
|
||||
creator: v.creator
|
||||
? {
|
||||
id: v.creator.id,
|
||||
@@ -2037,7 +2390,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
|
||||
@@ -2164,6 +2517,243 @@ export class AssetService {
|
||||
completionLastChangedBy,
|
||||
}
|
||||
}
|
||||
|
||||
async getAgentsMd(assetId: string): Promise<string | null> {
|
||||
const asset = await this.prismaClient.asset.findUnique({
|
||||
where: { id: assetId },
|
||||
select: { type: true },
|
||||
})
|
||||
if (!asset) throw new Error('Asset not found')
|
||||
if (asset.type !== AssetType.folder && asset.type !== AssetType.root) {
|
||||
throw new Error('AGENTS.md can only be stored on folders')
|
||||
}
|
||||
const record = await this.prismaClient.assetAgentMd.findUnique({
|
||||
where: { assetId },
|
||||
select: { content: true },
|
||||
})
|
||||
return record?.content ?? null
|
||||
}
|
||||
|
||||
async updateAgentsMd(assetId: string, content: string): Promise<{ content: string }> {
|
||||
const asset = await this.prismaClient.asset.findUnique({
|
||||
where: { id: assetId },
|
||||
select: { id: true, type: true },
|
||||
})
|
||||
if (!asset) throw new Error('Asset not found')
|
||||
if (asset.type !== AssetType.folder && asset.type !== AssetType.root) {
|
||||
throw new Error('AGENTS.md can only be stored on folders')
|
||||
}
|
||||
const trimmed = content.trim()
|
||||
if (trimmed.length === 0) {
|
||||
await this.prismaClient.assetAgentMd.deleteMany({
|
||||
where: { assetId },
|
||||
})
|
||||
return { content: '' }
|
||||
}
|
||||
const record = await this.prismaClient.assetAgentMd.upsert({
|
||||
where: { assetId },
|
||||
create: { assetId, content },
|
||||
update: { content },
|
||||
select: { content: true },
|
||||
})
|
||||
return { content: record.content }
|
||||
}
|
||||
|
||||
async getNestedAgentsMd(assetId: string): Promise<Array<{ path: string; content: string }>> {
|
||||
let currentId: string | null = assetId
|
||||
const nodes: Array<{
|
||||
id: string
|
||||
name: string
|
||||
type: AssetType
|
||||
parentId: string | null
|
||||
}> = []
|
||||
|
||||
while (currentId) {
|
||||
const node: {
|
||||
id: string
|
||||
name: string
|
||||
type: AssetType
|
||||
parentId: string | null
|
||||
} | null = await this.prismaClient.asset.findUnique({
|
||||
where: { id: currentId },
|
||||
select: { id: true, name: true, type: true, parentId: true },
|
||||
})
|
||||
if (!node) break
|
||||
nodes.unshift(node)
|
||||
currentId = node.parentId
|
||||
}
|
||||
|
||||
if (nodes.length === 0) return []
|
||||
|
||||
const agentMds = await this.prismaClient.assetAgentMd.findMany({
|
||||
where: { assetId: { in: nodes.map((n) => n.id) } },
|
||||
select: { assetId: true, content: true },
|
||||
})
|
||||
const agentMdMap = new Map(agentMds.map((m) => [m.assetId, m.content]))
|
||||
|
||||
const results: Array<{ path: string; content: string }> = []
|
||||
let currentFolderPath = ''
|
||||
|
||||
for (let i = 0; i < nodes.length; i++) {
|
||||
const node = nodes[i]
|
||||
let virtualPath: string
|
||||
|
||||
if (node.type === AssetType.root || i === 0) {
|
||||
currentFolderPath = ''
|
||||
virtualPath = '/AGENTS.md'
|
||||
} else {
|
||||
currentFolderPath = currentFolderPath
|
||||
? `${currentFolderPath}/${node.name}`
|
||||
: `/${node.name}`
|
||||
virtualPath = `${currentFolderPath}/AGENTS.md`
|
||||
}
|
||||
|
||||
const content = agentMdMap.get(node.id)
|
||||
if (content && content.trim().length > 0) {
|
||||
results.push({
|
||||
path: virtualPath,
|
||||
content: content.trim(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return results
|
||||
}
|
||||
|
||||
/**
|
||||
* Record a file view by user in project.
|
||||
* If the asset is a child file in a version stack, resolves to the version stack.
|
||||
* Enforces a maximum cap of 100 recent file items per (userId, projectId).
|
||||
*/
|
||||
async recordRecentView(userId: string, projectId: string, assetId: string): Promise<void> {
|
||||
const asset = await this.prismaClient.asset.findFirst({
|
||||
where: { id: assetId, projectId },
|
||||
select: {
|
||||
id: true,
|
||||
type: true,
|
||||
parentId: true,
|
||||
isDeleted: true,
|
||||
target: { select: { type: true, projectId: true, isDeleted: true } },
|
||||
},
|
||||
})
|
||||
|
||||
if (!asset || asset.isDeleted) return
|
||||
|
||||
const isFileAsset =
|
||||
asset.type === AssetType.file ||
|
||||
asset.type === AssetType.version_stack ||
|
||||
(asset.type === AssetType.symlink &&
|
||||
asset.target !== null &&
|
||||
(asset.target.type === AssetType.file || asset.target.type === AssetType.version_stack) &&
|
||||
asset.target.projectId === projectId &&
|
||||
!asset.target.isDeleted)
|
||||
if (!isFileAsset) return
|
||||
|
||||
let targetAssetId = asset.id
|
||||
|
||||
// If it's a file inside a version stack, record the version stack instead
|
||||
if (asset.type === AssetType.file && asset.parentId) {
|
||||
const parent = await this.prismaClient.asset.findFirst({
|
||||
where: { id: asset.parentId, projectId, type: AssetType.version_stack, isDeleted: false },
|
||||
select: { id: true },
|
||||
})
|
||||
if (parent) {
|
||||
targetAssetId = parent.id
|
||||
}
|
||||
}
|
||||
|
||||
const now = new Date()
|
||||
|
||||
// Upsert into recent_file_items
|
||||
await this.prismaClient.recentFileItem.upsert({
|
||||
where: {
|
||||
userIdProjectIdAssetId: {
|
||||
userId,
|
||||
projectId,
|
||||
assetId: targetAssetId,
|
||||
},
|
||||
},
|
||||
update: {
|
||||
viewedAt: now,
|
||||
},
|
||||
create: {
|
||||
userId,
|
||||
projectId,
|
||||
assetId: targetAssetId,
|
||||
viewedAt: now,
|
||||
},
|
||||
})
|
||||
|
||||
// Prune if more than 100 items for this (userId, projectId)
|
||||
const count = await this.prismaClient.recentFileItem.count({
|
||||
where: { userId, projectId },
|
||||
})
|
||||
|
||||
if (count > 100) {
|
||||
const itemsToKeep = await this.prismaClient.recentFileItem.findMany({
|
||||
where: { userId, projectId },
|
||||
orderBy: [{ viewedAt: 'desc' }, { id: 'desc' }],
|
||||
take: 100,
|
||||
select: { id: true },
|
||||
})
|
||||
const keepIds = itemsToKeep.map((item) => item.id)
|
||||
|
||||
await this.prismaClient.recentFileItem.deleteMany({
|
||||
where: {
|
||||
userId,
|
||||
projectId,
|
||||
id: { notIn: keepIds },
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* List recent files for user in project, paginated up to 100 total items.
|
||||
*/
|
||||
async listRecents(
|
||||
userId: string,
|
||||
projectId: string,
|
||||
req: ListRecentsRequest,
|
||||
): Promise<PaginatedData<AssetInfo[]>> {
|
||||
const where = {
|
||||
userId,
|
||||
projectId,
|
||||
asset: {
|
||||
isDeleted: false,
|
||||
projectId,
|
||||
},
|
||||
}
|
||||
|
||||
return paginateQuery(
|
||||
async (skip, take) => {
|
||||
if (skip >= 100) return []
|
||||
const effectiveTake = Math.min(take, 100 - skip)
|
||||
if (effectiveTake <= 0) return []
|
||||
|
||||
const recents = await this.prismaClient.recentFileItem.findMany({
|
||||
where,
|
||||
orderBy: [{ viewedAt: 'desc' }, { id: 'desc' }],
|
||||
skip,
|
||||
take: effectiveTake,
|
||||
include: {
|
||||
asset: {
|
||||
include: assetInclude,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const assets = recents.map((r) => r.asset).filter((a): a is AssetWithIncludes => !!a)
|
||||
|
||||
return await this.toAssetInfos(assets)
|
||||
},
|
||||
async () => {
|
||||
const total = await this.prismaClient.recentFileItem.count({ where })
|
||||
return Math.min(total, 100)
|
||||
},
|
||||
req,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export const assetService = new AssetService()
|
||||
|
||||
@@ -0,0 +1,278 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { prisma, AssetType, AssetStatus } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { assetService } from './asset'
|
||||
import { projectService } from '../project/project'
|
||||
|
||||
describe('AssetService - Recently Viewed', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
async function setupProject() {
|
||||
const user1 = await prisma.user.create({
|
||||
data: { name: 'User 1', email: 'user1@example.com' },
|
||||
})
|
||||
const user2 = await prisma.user.create({
|
||||
data: { name: 'User 2', email: 'user2@example.com' },
|
||||
})
|
||||
const team = await prisma.team.create({
|
||||
data: {
|
||||
name: 'Test Team',
|
||||
settings: {
|
||||
transcode: { videoStrategy: 'best_match' },
|
||||
},
|
||||
sandbox: { create: {} },
|
||||
},
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: {
|
||||
teamId: team.id,
|
||||
userId: user1.id,
|
||||
role: 'owner',
|
||||
scope: 'team',
|
||||
},
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: {
|
||||
teamId: team.id,
|
||||
userId: user2.id,
|
||||
role: 'editor',
|
||||
scope: 'team',
|
||||
},
|
||||
})
|
||||
|
||||
const project = await projectService.createProject(user1, {
|
||||
name: 'Test Project',
|
||||
teamId: team.id,
|
||||
})
|
||||
|
||||
return { user1, user2, team, project }
|
||||
}
|
||||
|
||||
it('records recent file view and returns it in descending order', async () => {
|
||||
const { user1, project } = await setupProject()
|
||||
|
||||
const file1 = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'file1.mp4',
|
||||
type: AssetType.file,
|
||||
status: 'processed',
|
||||
projectId: project.id,
|
||||
parentId: project.rootFolder!,
|
||||
},
|
||||
})
|
||||
const file2 = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'file2.mp4',
|
||||
type: AssetType.file,
|
||||
status: 'processed',
|
||||
projectId: project.id,
|
||||
parentId: project.rootFolder!,
|
||||
},
|
||||
})
|
||||
|
||||
await assetService.recordRecentView(user1.id, project.id, file1.id)
|
||||
await assetService.recordRecentView(user1.id, project.id, file2.id)
|
||||
|
||||
const list = await assetService.listRecents(user1.id, project.id, {})
|
||||
expect(list.data.length).toBe(2)
|
||||
expect(list.data[0].id).toBe(file2.id)
|
||||
expect(list.data[1].id).toBe(file1.id)
|
||||
expect(list.pageInfo.total).toBe(2)
|
||||
})
|
||||
|
||||
it('updates viewedAt when viewing the same file again', async () => {
|
||||
const { user1, project } = await setupProject()
|
||||
|
||||
const file1 = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'file1.mp4',
|
||||
type: AssetType.file,
|
||||
status: 'processed',
|
||||
projectId: project.id,
|
||||
parentId: project.rootFolder!,
|
||||
},
|
||||
})
|
||||
const file2 = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'file2.mp4',
|
||||
type: AssetType.file,
|
||||
status: 'processed',
|
||||
projectId: project.id,
|
||||
parentId: project.rootFolder!,
|
||||
},
|
||||
})
|
||||
|
||||
await assetService.recordRecentView(user1.id, project.id, file1.id)
|
||||
await assetService.recordRecentView(user1.id, project.id, file2.id)
|
||||
// View file1 again
|
||||
await assetService.recordRecentView(user1.id, project.id, file1.id)
|
||||
|
||||
const list = await assetService.listRecents(user1.id, project.id, {})
|
||||
expect(list.data.length).toBe(2)
|
||||
expect(list.data[0].id).toBe(file1.id)
|
||||
expect(list.data[1].id).toBe(file2.id)
|
||||
})
|
||||
|
||||
it('records version stack when viewing a child version file', async () => {
|
||||
const { user1, project } = await setupProject()
|
||||
|
||||
const stack = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'version_stack',
|
||||
type: AssetType.version_stack,
|
||||
status: 'processed',
|
||||
projectId: project.id,
|
||||
parentId: project.rootFolder!,
|
||||
},
|
||||
})
|
||||
|
||||
const version1 = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'v1.mp4',
|
||||
type: AssetType.file,
|
||||
status: 'processed',
|
||||
projectId: project.id,
|
||||
parentId: stack.id,
|
||||
},
|
||||
})
|
||||
|
||||
await assetService.recordRecentView(user1.id, project.id, version1.id)
|
||||
|
||||
const list = await assetService.listRecents(user1.id, project.id, {})
|
||||
expect(list.data.length).toBe(1)
|
||||
expect(list.data[0].id).toBe(stack.id)
|
||||
expect(list.data[0].type).toBe(AssetType.version_stack)
|
||||
})
|
||||
|
||||
it('isolates recents per user', async () => {
|
||||
const { user1, user2, project } = await setupProject()
|
||||
|
||||
const file1 = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'file1.mp4',
|
||||
type: AssetType.file,
|
||||
status: 'processed',
|
||||
projectId: project.id,
|
||||
parentId: project.rootFolder!,
|
||||
},
|
||||
})
|
||||
|
||||
await assetService.recordRecentView(user1.id, project.id, file1.id)
|
||||
|
||||
const user1List = await assetService.listRecents(user1.id, project.id, {})
|
||||
const user2List = await assetService.listRecents(user2.id, project.id, {})
|
||||
|
||||
expect(user1List.data.length).toBe(1)
|
||||
expect(user2List.data.length).toBe(0)
|
||||
})
|
||||
|
||||
it('does not record assets from another project', async () => {
|
||||
const { user1, team, project } = await setupProject()
|
||||
const otherProject = await projectService.createProject(user1, {
|
||||
name: 'Other Project',
|
||||
teamId: team.id,
|
||||
})
|
||||
const foreignFile = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'foreign-file.mp4',
|
||||
type: AssetType.file,
|
||||
status: AssetStatus.processed,
|
||||
projectId: otherProject.id,
|
||||
parentId: otherProject.rootFolder!,
|
||||
},
|
||||
})
|
||||
|
||||
await assetService.recordRecentView(user1.id, project.id, foreignFile.id)
|
||||
|
||||
const list = await assetService.listRecents(user1.id, project.id, {})
|
||||
expect(list.data).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('does not record non-file assets', async () => {
|
||||
const { user1, project } = await setupProject()
|
||||
const folder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'folder',
|
||||
type: AssetType.folder,
|
||||
status: AssetStatus.processed,
|
||||
projectId: project.id,
|
||||
parentId: project.rootFolder!,
|
||||
},
|
||||
})
|
||||
|
||||
await assetService.recordRecentView(user1.id, project.id, folder.id)
|
||||
|
||||
const list = await assetService.listRecents(user1.id, project.id, {})
|
||||
expect(list.data).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('does not return soft-deleted files in recents', async () => {
|
||||
const { user1, project } = await setupProject()
|
||||
|
||||
const file1 = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'file1.mp4',
|
||||
type: AssetType.file,
|
||||
status: 'processed',
|
||||
projectId: project.id,
|
||||
parentId: project.rootFolder!,
|
||||
},
|
||||
})
|
||||
|
||||
await assetService.recordRecentView(user1.id, project.id, file1.id)
|
||||
|
||||
// Soft delete file1
|
||||
await prisma.asset.update({
|
||||
where: { id: file1.id },
|
||||
data: { isDeleted: true, status: 'trashed' },
|
||||
})
|
||||
|
||||
const list = await assetService.listRecents(user1.id, project.id, {})
|
||||
expect(list.data.length).toBe(0)
|
||||
})
|
||||
|
||||
it('caps recents at 100 items per user/project', async () => {
|
||||
const { user1, project } = await setupProject()
|
||||
|
||||
// Batch create 105 assets
|
||||
const assetsData = Array.from({ length: 105 }, (_, i) => ({
|
||||
name: `file_${i}.mp4`,
|
||||
type: AssetType.file,
|
||||
status: AssetStatus.processed,
|
||||
projectId: project.id,
|
||||
parentId: project.rootFolder!,
|
||||
}))
|
||||
await prisma.asset.createMany({ data: assetsData })
|
||||
const allAssets = await prisma.asset.findMany({
|
||||
where: { projectId: project.id, parentId: project.rootFolder! },
|
||||
orderBy: { id: 'asc' },
|
||||
})
|
||||
|
||||
// Seed 100 items in recentFileItem
|
||||
const baseDate = new Date('2026-01-01T00:00:00Z')
|
||||
await prisma.recentFileItem.createMany({
|
||||
data: allAssets.slice(0, 100).map((a, i) => ({
|
||||
userId: user1.id,
|
||||
projectId: project.id,
|
||||
assetId: a.id,
|
||||
viewedAt: new Date(baseDate.getTime() + i * 1000),
|
||||
})),
|
||||
})
|
||||
|
||||
// Now record view for the 101st asset to trigger pruning
|
||||
const newAsset = allAssets[100]
|
||||
await assetService.recordRecentView(user1.id, project.id, newAsset.id)
|
||||
|
||||
const count = await prisma.recentFileItem.count({
|
||||
where: { userId: user1.id, projectId: project.id },
|
||||
})
|
||||
expect(count).toBe(100)
|
||||
|
||||
const list = await assetService.listRecents(user1.id, project.id, { first: 100 })
|
||||
expect(list.data.length).toBe(100)
|
||||
// The most recently viewed file should be newAsset
|
||||
expect(list.data[0].id).toBe(newAsset.id)
|
||||
// The oldest file (allAssets[0]) should have been pruned
|
||||
expect(list.data.some((d) => d.id === allAssets[0].id)).toBe(false)
|
||||
}, 15000)
|
||||
})
|
||||
@@ -0,0 +1,249 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { AssetType } from '@shumai/db'
|
||||
import { dedupeSymlinksToTarget } from './symlink'
|
||||
|
||||
async function setupShareFolder(projectId: string, fileCount: number) {
|
||||
const shareRoot = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'share-root',
|
||||
type: AssetType.share_root,
|
||||
projectId,
|
||||
status: 'uploaded',
|
||||
fileCount,
|
||||
},
|
||||
})
|
||||
return shareRoot
|
||||
}
|
||||
|
||||
describe('dedupeSymlinksToTarget', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
async function setupProject() {
|
||||
const team = await prisma.team.create({ data: { name: 'Team ' + Date.now() } })
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'Project ' + Date.now(), teamId: team.id },
|
||||
})
|
||||
const root = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'root',
|
||||
type: AssetType.folder,
|
||||
projectId: project.id,
|
||||
status: 'uploaded',
|
||||
},
|
||||
})
|
||||
const fileA = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'a.txt',
|
||||
type: AssetType.file,
|
||||
parentId: root.id,
|
||||
projectId: project.id,
|
||||
status: 'uploaded',
|
||||
sizeByte: 10,
|
||||
},
|
||||
})
|
||||
const fileB = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'b.txt',
|
||||
type: AssetType.file,
|
||||
parentId: root.id,
|
||||
projectId: project.id,
|
||||
status: 'uploaded',
|
||||
sizeByte: 20,
|
||||
},
|
||||
})
|
||||
return { project, root, fileA, fileB }
|
||||
}
|
||||
|
||||
it('repoints one symlink per parent and deletes duplicates, decrementing fileCount once', async () => {
|
||||
const { project, root, fileA, fileB } = await setupProject()
|
||||
const shareRoot = await setupShareFolder(project.id, 2)
|
||||
|
||||
const symA = await prisma.asset.create({
|
||||
data: {
|
||||
name: fileA.name,
|
||||
type: AssetType.symlink,
|
||||
parentId: shareRoot.id,
|
||||
targetId: fileA.id,
|
||||
projectId: project.id,
|
||||
status: 'uploaded',
|
||||
},
|
||||
})
|
||||
const symB = await prisma.asset.create({
|
||||
data: {
|
||||
name: fileB.name,
|
||||
type: AssetType.symlink,
|
||||
parentId: shareRoot.id,
|
||||
targetId: fileB.id,
|
||||
projectId: project.id,
|
||||
status: 'uploaded',
|
||||
},
|
||||
})
|
||||
|
||||
const stack = await prisma.asset.create({
|
||||
data: {
|
||||
name: '',
|
||||
type: AssetType.version_stack,
|
||||
parentId: root.id,
|
||||
projectId: project.id,
|
||||
status: 'uploaded',
|
||||
fileCount: 2,
|
||||
sizeByte: 30,
|
||||
},
|
||||
})
|
||||
|
||||
await prisma.$transaction((tx) =>
|
||||
dedupeSymlinksToTarget(tx, { targetIds: [fileA.id, fileB.id], newTargetId: stack.id }),
|
||||
)
|
||||
|
||||
// First symlink repointed to the stack, second deleted
|
||||
const repointed = await prisma.asset.findUnique({ where: { id: symA.id } })
|
||||
expect(repointed?.targetId).toBe(stack.id)
|
||||
expect(await prisma.asset.findUnique({ where: { id: symB.id } })).toBeNull()
|
||||
|
||||
// fileCount decremented exactly once (2 -> 1)
|
||||
const updatedShareRoot = await prisma.asset.findUnique({ where: { id: shareRoot.id } })
|
||||
expect(updatedShareRoot?.fileCount).toBe(1)
|
||||
})
|
||||
|
||||
it('deletes a file symlink when the parent already shows the stack', async () => {
|
||||
const { project, root, fileA } = await setupProject()
|
||||
const shareRoot = await setupShareFolder(project.id, 2)
|
||||
|
||||
const stack = await prisma.asset.create({
|
||||
data: {
|
||||
name: '',
|
||||
type: AssetType.version_stack,
|
||||
parentId: root.id,
|
||||
projectId: project.id,
|
||||
status: 'uploaded',
|
||||
fileCount: 1,
|
||||
sizeByte: 10,
|
||||
},
|
||||
})
|
||||
// Share already contains a symlink to the stack
|
||||
const stackSymlink = await prisma.asset.create({
|
||||
data: {
|
||||
name: '',
|
||||
type: AssetType.symlink,
|
||||
parentId: shareRoot.id,
|
||||
targetId: stack.id,
|
||||
projectId: project.id,
|
||||
status: 'uploaded',
|
||||
},
|
||||
})
|
||||
// And a symlink to the file being moved into the stack
|
||||
const fileSymlink = await prisma.asset.create({
|
||||
data: {
|
||||
name: fileA.name,
|
||||
type: AssetType.symlink,
|
||||
parentId: shareRoot.id,
|
||||
targetId: fileA.id,
|
||||
projectId: project.id,
|
||||
status: 'uploaded',
|
||||
},
|
||||
})
|
||||
|
||||
await prisma.$transaction((tx) =>
|
||||
dedupeSymlinksToTarget(tx, { targetIds: [fileA.id], newTargetId: stack.id }),
|
||||
)
|
||||
|
||||
// File symlink deleted, stack symlink untouched
|
||||
expect(await prisma.asset.findUnique({ where: { id: fileSymlink.id } })).toBeNull()
|
||||
const updatedStackSymlink = await prisma.asset.findUnique({ where: { id: stackSymlink.id } })
|
||||
expect(updatedStackSymlink?.targetId).toBe(stack.id)
|
||||
|
||||
// fileCount decremented once (2 -> 1)
|
||||
const updatedShareRoot = await prisma.asset.findUnique({ where: { id: shareRoot.id } })
|
||||
expect(updatedShareRoot?.fileCount).toBe(1)
|
||||
})
|
||||
|
||||
it('repoints symlinks in different share folders without changing fileCounts', async () => {
|
||||
const { project, root, fileA, fileB } = await setupProject()
|
||||
const share1 = await setupShareFolder(project.id, 1)
|
||||
const share2 = await setupShareFolder(project.id, 1)
|
||||
|
||||
const sym1 = await prisma.asset.create({
|
||||
data: {
|
||||
name: fileA.name,
|
||||
type: AssetType.symlink,
|
||||
parentId: share1.id,
|
||||
targetId: fileA.id,
|
||||
projectId: project.id,
|
||||
status: 'uploaded',
|
||||
},
|
||||
})
|
||||
const sym2 = await prisma.asset.create({
|
||||
data: {
|
||||
name: fileB.name,
|
||||
type: AssetType.symlink,
|
||||
parentId: share2.id,
|
||||
targetId: fileB.id,
|
||||
projectId: project.id,
|
||||
status: 'uploaded',
|
||||
},
|
||||
})
|
||||
|
||||
const stack = await prisma.asset.create({
|
||||
data: {
|
||||
name: '',
|
||||
type: AssetType.version_stack,
|
||||
parentId: root.id,
|
||||
projectId: project.id,
|
||||
status: 'uploaded',
|
||||
fileCount: 2,
|
||||
sizeByte: 30,
|
||||
},
|
||||
})
|
||||
|
||||
await prisma.$transaction((tx) =>
|
||||
dedupeSymlinksToTarget(tx, { targetIds: [fileA.id, fileB.id], newTargetId: stack.id }),
|
||||
)
|
||||
|
||||
expect((await prisma.asset.findUnique({ where: { id: sym1.id } }))?.targetId).toBe(stack.id)
|
||||
expect((await prisma.asset.findUnique({ where: { id: sym2.id } }))?.targetId).toBe(stack.id)
|
||||
expect((await prisma.asset.findUnique({ where: { id: share1.id } }))?.fileCount).toBe(1)
|
||||
expect((await prisma.asset.findUnique({ where: { id: share2.id } }))?.fileCount).toBe(1)
|
||||
})
|
||||
|
||||
it('sets the provided name on repointed symlinks', async () => {
|
||||
const { project, root, fileA } = await setupProject()
|
||||
const shareRoot = await setupShareFolder(project.id, 1)
|
||||
|
||||
const sym = await prisma.asset.create({
|
||||
data: {
|
||||
name: fileA.name,
|
||||
type: AssetType.symlink,
|
||||
parentId: shareRoot.id,
|
||||
targetId: fileA.id,
|
||||
projectId: project.id,
|
||||
status: 'uploaded',
|
||||
},
|
||||
})
|
||||
|
||||
const stack = await prisma.asset.create({
|
||||
data: {
|
||||
name: '',
|
||||
type: AssetType.version_stack,
|
||||
parentId: root.id,
|
||||
projectId: project.id,
|
||||
status: 'uploaded',
|
||||
fileCount: 1,
|
||||
sizeByte: 10,
|
||||
},
|
||||
})
|
||||
|
||||
await prisma.$transaction((tx) =>
|
||||
dedupeSymlinksToTarget(tx, {
|
||||
targetIds: [fileA.id],
|
||||
newTargetId: stack.id,
|
||||
name: '',
|
||||
}),
|
||||
)
|
||||
|
||||
const updatedSym = await prisma.asset.findUnique({ where: { id: sym.id } })
|
||||
expect(updatedSym?.targetId).toBe(stack.id)
|
||||
expect(updatedSym?.name).toBe('')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,59 @@
|
||||
import { Prisma } from '@shumai/db'
|
||||
import { AssetType } from '@shumai/db'
|
||||
|
||||
interface DedupeSymlinksParams {
|
||||
/** Files being merged into a version stack — symlinks pointing at them are the candidates. */
|
||||
targetIds: string[]
|
||||
/** The version stack the files are moving into. */
|
||||
newTargetId: string
|
||||
/** Optional name to set on repointed symlinks ('' for stacks — display name comes from the latest version). */
|
||||
name?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* When files are merged into a version stack, symlinks in share folders that
|
||||
* pointed at those files must either be repointed to the stack (one per parent)
|
||||
* or deleted as duplicates. Per parent folder: if the parent already shows the
|
||||
* stack (either before this call or after the first repoint), delete the
|
||||
* incoming symlink and decrement the parent's fileCount; otherwise repoint the
|
||||
* first symlink to the stack.
|
||||
*/
|
||||
export async function dedupeSymlinksToTarget(
|
||||
tx: Prisma.TransactionClient,
|
||||
{ targetIds, newTargetId, name }: DedupeSymlinksParams,
|
||||
): Promise<void> {
|
||||
const existingSymlinks = await tx.asset.findMany({
|
||||
where: { targetId: { in: targetIds }, type: AssetType.symlink },
|
||||
orderBy: { id: 'asc' },
|
||||
})
|
||||
if (existingSymlinks.length === 0) return
|
||||
|
||||
// Parents that already display the stack (or will after the first repoint).
|
||||
const stackSymlinkParents = new Set(
|
||||
(
|
||||
await tx.asset.findMany({
|
||||
where: { targetId: newTargetId, type: AssetType.symlink },
|
||||
select: { parentId: true },
|
||||
})
|
||||
)
|
||||
.map((s) => s.parentId)
|
||||
.filter((id): id is string => !!id),
|
||||
)
|
||||
|
||||
for (const symlink of existingSymlinks) {
|
||||
if (!symlink.parentId) continue
|
||||
if (stackSymlinkParents.has(symlink.parentId)) {
|
||||
await tx.asset.delete({ where: { id: symlink.id } })
|
||||
await tx.asset.update({
|
||||
where: { id: symlink.parentId },
|
||||
data: { fileCount: { decrement: 1 } },
|
||||
})
|
||||
} else {
|
||||
stackSymlinkParents.add(symlink.parentId)
|
||||
await tx.asset.update({
|
||||
where: { id: symlink.id },
|
||||
data: { targetId: newTargetId, ...(name !== undefined ? { name } : {}) },
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
|
||||
@@ -558,6 +613,53 @@ describe('ChatService', () => {
|
||||
expect(mapEntryToMessage(leafRecord)).toBeNull()
|
||||
})
|
||||
|
||||
it('should map shumai_message custom_message entries with clean text and structured details', () => {
|
||||
const entryRecord = {
|
||||
id: 'entry-shumai-msg',
|
||||
type: 'custom_message',
|
||||
parentId: null,
|
||||
createdAt: new Date('2026-07-07T00:05:00.000Z'),
|
||||
data: {
|
||||
customType: 'shumai_message',
|
||||
content: 'Please adjust color grading',
|
||||
display: true,
|
||||
details: {
|
||||
user: { id: 'u1', name: 'Alice', role: 'editor' },
|
||||
currentAsset: { id: 'a1', name: 'video.mp4', type: 'file' },
|
||||
position: { type: 'time', seconds: 12.5 },
|
||||
},
|
||||
},
|
||||
} as unknown as Parameters<typeof mapEntryToMessage>[0]
|
||||
|
||||
const msg = mapEntryToMessage(entryRecord)
|
||||
expect(msg).toBeDefined()
|
||||
expect(msg?.id).toBe('entry-shumai-msg')
|
||||
expect(msg?.role).toBe('custom')
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
expect((msg as any)?.customType).toBe('shumai_message')
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
expect((msg as any)?.content).toBe('Please adjust color grading')
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
expect((msg as any)?.details?.user?.name).toBe('Alice')
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
expect((msg as any)?.details?.position?.seconds).toBe(12.5)
|
||||
})
|
||||
|
||||
it('should skip legacy context custom_message in mapEntryToMessage', () => {
|
||||
const entryRecord = {
|
||||
id: 'entry-legacy-context',
|
||||
type: 'custom_message',
|
||||
parentId: null,
|
||||
createdAt: new Date('2026-07-07T00:05:00.000Z'),
|
||||
data: {
|
||||
customType: 'context',
|
||||
content: 'System context prompt...',
|
||||
},
|
||||
} as unknown as Parameters<typeof mapEntryToMessage>[0]
|
||||
|
||||
expect(mapEntryToMessage(entryRecord)).toBeNull()
|
||||
})
|
||||
|
||||
describe('getNewSessionMessages', () => {
|
||||
it('returns new messages and lastEntryId', async () => {
|
||||
const { user, team, project } = await setupBasicData()
|
||||
@@ -688,6 +790,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 +823,170 @@ 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/)
|
||||
})
|
||||
|
||||
it('safely maps entries without message object or with customType shumai_message', () => {
|
||||
// 1. Entry with type: 'message' but customType: 'shumai_message'
|
||||
const legacyEntry = {
|
||||
id: 'legacy-1',
|
||||
sessionId: 'sess-1',
|
||||
assetId: null,
|
||||
parentId: null,
|
||||
type: 'message',
|
||||
data: {
|
||||
customType: 'shumai_message',
|
||||
content: 'Hello legacy',
|
||||
display: true,
|
||||
details: { user: { id: 'u1', name: 'User 1' } },
|
||||
},
|
||||
createdAt: new Date(),
|
||||
}
|
||||
|
||||
const msg1 = mapEntryToMessage(legacyEntry)
|
||||
expect(msg1).toBeDefined()
|
||||
expect(msg1?.role).toBe('custom')
|
||||
if (msg1 && msg1.role === 'custom') {
|
||||
expect(msg1.customType).toBe('shumai_message')
|
||||
expect(msg1.content).toBe('Hello legacy')
|
||||
expect(msg1.details).toEqual({ user: { id: 'u1', name: 'User 1' } })
|
||||
}
|
||||
|
||||
// 2. Entry with type: 'message' but empty data / no message
|
||||
const emptyEntry = {
|
||||
id: 'empty-1',
|
||||
sessionId: 'sess-1',
|
||||
assetId: null,
|
||||
parentId: null,
|
||||
type: 'message',
|
||||
data: {},
|
||||
createdAt: new Date(),
|
||||
}
|
||||
|
||||
const msg2 = mapEntryToMessage(emptyEntry)
|
||||
expect(msg2).toBeNull()
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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>>
|
||||
|
||||
@@ -24,11 +30,31 @@ export function buildSessionMessages(pathEntries: PathEntry[]): ChatMessage[] {
|
||||
const appendMessage = (entry: PathEntry) => {
|
||||
const timestampMs = new Date(entry.timestamp).getTime()
|
||||
if (entry.type === 'message') {
|
||||
messages.push({
|
||||
...entry.message,
|
||||
id: entry.id,
|
||||
timestamp: entry.message.timestamp || timestampMs,
|
||||
} as unknown as ChatMessage)
|
||||
if ((entry as unknown as { customType?: string }).customType === 'shumai_message') {
|
||||
const customEntry = entry as unknown as {
|
||||
customType: string
|
||||
content: string
|
||||
display?: boolean
|
||||
details?: Record<string, unknown>
|
||||
}
|
||||
messages.push({
|
||||
id: entry.id,
|
||||
role: 'custom',
|
||||
customType: customEntry.customType,
|
||||
content: customEntry.content,
|
||||
display: customEntry.display,
|
||||
details: customEntry.details,
|
||||
timestamp: timestampMs,
|
||||
} as unknown as ChatMessage)
|
||||
return
|
||||
}
|
||||
if (entry.message) {
|
||||
messages.push({
|
||||
...entry.message,
|
||||
id: entry.id,
|
||||
timestamp: entry.message.timestamp || timestampMs,
|
||||
} as unknown as ChatMessage)
|
||||
}
|
||||
} else if (entry.type === 'custom_message') {
|
||||
if (entry.customType === 'context') return
|
||||
messages.push({
|
||||
@@ -111,9 +137,13 @@ export function mapEntryToMessage(
|
||||
entryRecord: Prisma.AgentSessionEntryGetPayload<Record<string, never>>,
|
||||
): ChatMessage | null {
|
||||
const payload = (entryRecord.data as Record<string, unknown>) || {}
|
||||
let type = (entryRecord.type || 'message') as SessionTreeEntry['type']
|
||||
if (type === 'message' && payload.customType === 'shumai_message') {
|
||||
type = 'custom_message'
|
||||
}
|
||||
const entryObj = {
|
||||
id: entryRecord.id,
|
||||
type: (entryRecord.type || 'message') as SessionTreeEntry['type'],
|
||||
type,
|
||||
parentId: entryRecord.parentId,
|
||||
timestamp: entryRecord.createdAt.toISOString(),
|
||||
...payload,
|
||||
@@ -281,7 +311,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 +322,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 },
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user