2026-11-11 16:05:18 +08:00
import type { ToolRegistration } from '@earendil-works/pi-durable'
import { Harness , createRegistry } from '@earendil-works/pi-durable'
import { BACKGROUND_CONTEXT } from '@earendil-works/chord/context'
import { createModels } from '@earendil-works/pi-ai'
import { agentSessionService } from '@shumai/core/src/agent/session-service'
import { invokeTool } from '@shumai/core/src/agent/tool-test-utils'
import { logger } from '@shumai/core/src/logger'
import { getShumaiMessage } from '@shumai/dtos'
import { DBOS , DBOSError , runInLocalTaskContext , triggerLocalCancel } from '@shumai/workflow-core'
import { beforeEach , describe , expect , it , vi } from 'vitest'
import * as piAgent from '../runtime'
import * as commentContext from '../comment-context'
import { mockAgentSession } from '../testing/native-runtime'
2026-06-03 15:48:25 +08:00
import {
agentChatActivity ,
type AgentExecutionContext ,
2026-11-11 16:05:18 +08:00
autofillAiActivity ,
2026-06-03 15:48:25 +08:00
createCommentActivity ,
2026-11-11 16:05:18 +08:00
deleteCommentActivity ,
formatProjectContextPrompt ,
2026-07-11 20:54:09 +08:00
generateSessionNameActivity ,
type GenerateSessionNameParams ,
2026-11-11 16:05:18 +08:00
getAgentAutofillContextActivity ,
getAgentChatContextActivity ,
getAssetActivity ,
getAssetPathContextActivity ,
getAssetPathHierarchyActivity ,
getCommentActivity ,
getProjectAutofillFieldsActivity ,
2026-07-27 11:24:48 +08:00
getUserTeamInfoActivity ,
2026-11-11 16:05:18 +08:00
initializeAgentSessionActivity ,
updateAssetMetadataActivity ,
updateCommentActivity ,
2026-06-03 15:48:25 +08:00
} from './agent'
2026-07-14 10:25:06 +08:00
2026-06-03 16:17:25 +08:00
import {
2026-11-11 16:05:18 +08:00
type Asset ,
2026-06-03 16:17:25 +08:00
AssetStatus ,
2026-11-11 16:05:18 +08:00
AssetType ,
prisma ,
type Project ,
2026-06-03 16:17:25 +08:00
type Team ,
type User ,
} from '@shumai/db'
2026-06-03 15:48:25 +08:00
import { setupTestDbHooks } from '@shumai/db/test'
2026-05-19 16:05:09 +08:00
2026-11-11 16:05:18 +08:00
vi . mock ( '../runtime' , async () => {
const actual = await vi . importActual ( '../runtime' )
2026-05-27 23:40:14 +08:00
return {
... actual ,
createAgentSession : vi.fn (),
fieldsToTypeBoxSchema : vi.fn (),
}
})
2026-05-19 16:05:09 +08:00
describe ( 'Agent Activities' , () => {
beforeEach (() => {
vi . clearAllMocks ()
2026-11-11 16:05:18 +08:00
vi . spyOn ( agentSessionService , 'getEntries' ). mockResolvedValue ([])
vi . spyOn ( commentContext , 'synchronizeCommentContext' ). mockResolvedValue ()
2026-05-19 16:05:09 +08:00
})
2026-05-27 23:40:14 +08:00
it ( 'should call agentChatActivity and prompt the harness' , async () => {
const mockHarness = {
2026-07-23 11:11:48 +08:00
subscribe : vi.fn (),
2026-05-27 23:40:14 +08:00
prompt : vi.fn (). mockResolvedValue ({
content : [{ type : 'text' , text : 'AI response' }],
usage : { input : 10 , output : 20 },
}),
}
const mockSession = {
getEntries : vi.fn (). mockResolvedValue ([]),
getStorage : vi.fn (). mockReturnValue ({ sessionId : 'mock-session-id' }),
}
2026-11-11 16:05:18 +08:00
vi . mocked ( piAgent . createAgentSession ). mockResolvedValue (
mockAgentSession ( mockHarness , mockSession ),
)
2026-05-19 16:05:09 +08:00
2026-05-27 23:40:14 +08:00
const context = {
agent : { id : 'b1' , provider : { name : 'google' }, modelRef : { modelId : 'gemini' } },
dbProviders : [],
teamSkills : [],
allowedDomains : [],
2026-05-28 11:43:42 +08:00
} as unknown as AgentExecutionContext
2026-05-27 23:40:14 +08:00
const res = await agentChatActivity ({
2026-05-19 16:05:09 +08:00
teamId : 't1' ,
agentId : 'b1' ,
message : 'Hi' ,
imageUrls : [],
projectId : 'p1' ,
folderId : 'f1' ,
2026-05-21 22:51:40 +08:00
sessionId : 'mock-session-id' ,
2026-05-27 23:40:14 +08:00
context ,
2026-05-19 16:05:09 +08:00
})
2026-05-27 23:40:14 +08:00
expect ( res . text ). toBe ( 'AI response' )
expect ( res . usage . inputTokens ). toBe ( 10 )
expect ( res . usage . outputTokens ). toBe ( 20 )
expect ( piAgent . createAgentSession ). toHaveBeenCalled ()
})
2026-11-11 16:05:18 +08:00
it ( 'reports committed native model usage' , async () => {
const usage = {
input : 150 ,
output : 75 ,
cacheRead : 25 ,
totalTokens : 225 ,
cost : { total : 0.0015 },
2026-07-23 11:02:54 +08:00
}
2026-11-11 16:05:18 +08:00
const model = {
prompt : vi.fn (). mockResolvedValue ({ content : [{ type : 'text' , text : 'Response' }], usage }),
2026-07-23 11:02:54 +08:00
}
2026-11-11 16:05:18 +08:00
vi . mocked ( piAgent . createAgentSession ). mockResolvedValue ( mockAgentSession ( model ))
2026-07-23 11:02:54 +08:00
const context = {
agent : { id : 'b1' , provider : { name : 'google' }, modelRef : { modelId : 'gemini' } },
dbProviders : [],
teamSkills : [],
allowedDomains : [],
} as unknown as AgentExecutionContext
2026-11-11 16:05:18 +08:00
const response = await agentChatActivity ({
2026-07-23 11:02:54 +08:00
teamId : 'team123' ,
agentId : 'b1' ,
message : 'Hi' ,
imageUrls : [],
projectId : 'p1' ,
folderId : 'f1' ,
sessionId : 'mock-session-id' ,
context ,
})
2026-11-11 16:05:18 +08:00
expect ( response . usage ). toMatchObject ({
2026-07-23 11:02:54 +08:00
inputTokens : 150 ,
outputTokens : 75 ,
cacheReadTokens : 25 ,
cost : 0.0015 ,
})
2026-11-11 16:05:18 +08:00
expect ( response . usage . totalTokens ). toBe ( 225 )
2026-07-23 11:02:54 +08:00
})
2026-07-14 10:25:06 +08:00
it ( 'should register local cancellation handler and call harness.abort when cancelled in local mode' , async () => {
2026-07-14 10:32:18 +08:00
let resolvePrompt !: ( value : {
content : Array < { type : string ; text : string } | { type : string } >
usage : { input : number ; output : number }
stopReason? : string
errorMessage? : string
}) => void
const promptPromise = new Promise < Parameters < typeof resolvePrompt > [ 0 ] >(( resolve ) => {
2026-07-14 10:25:06 +08:00
resolvePrompt = resolve
})
const mockHarness = {
2026-07-23 11:11:48 +08:00
subscribe : vi.fn (),
2026-07-14 10:25:06 +08:00
prompt : vi.fn (). mockReturnValue ( promptPromise ),
abort : vi.fn (),
}
const mockSession = {
getEntries : vi.fn (). mockResolvedValue ([]),
getStorage : vi.fn (). mockReturnValue ({ sessionId : 'mock-session-id' }),
}
2026-11-11 16:05:18 +08:00
vi . mocked ( piAgent . createAgentSession ). mockResolvedValue (
mockAgentSession ( mockHarness , mockSession ),
)
2026-07-14 10:25:06 +08:00
const context = {
agent : { id : 'b1' , provider : { name : 'google' }, modelRef : { modelId : 'gemini' } },
dbProviders : [],
teamSkills : [],
allowedDomains : [],
} as unknown as AgentExecutionContext
const executionPromise = agentChatActivity ({
taskId : 'task-123' ,
teamId : 't1' ,
agentId : 'b1' ,
message : 'Hi' ,
imageUrls : [],
projectId : 'p1' ,
folderId : 'f1' ,
sessionId : 'mock-session-id' ,
context ,
})
// Yield to let the asynchronous setup register the cancel handler
await new Promise (( resolve ) => setTimeout ( resolve , 50 ))
// Simulate user cancellation
const cancelled = triggerLocalCancel ( 'task-123' )
expect ( cancelled ). toBe ( true )
expect ( mockHarness . abort ). toHaveBeenCalled ()
// Resolve the prompt promise to allow the activity to finish clean
resolvePrompt ({
content : [{ type : 'text' , text : 'AI response' }],
usage : { input : 10 , output : 20 },
})
await executionPromise
})
2026-10-19 15:35:08 +08:00
it ( 'should listen to abort signal and call harness.abort when cancelled' , async () => {
2026-07-14 10:32:18 +08:00
let resolvePrompt !: ( value : {
content : Array < { type : string ; text : string } | { type : string } >
usage : { input : number ; output : number }
stopReason? : string
errorMessage? : string
}) => void
const promptPromise = new Promise < Parameters < typeof resolvePrompt > [ 0 ] >(( resolve ) => {
2026-07-14 10:25:06 +08:00
resolvePrompt = resolve
})
const mockHarness = {
2026-07-23 11:11:48 +08:00
subscribe : vi.fn (),
2026-07-14 10:25:06 +08:00
prompt : vi.fn (). mockReturnValue ( promptPromise ),
abort : vi.fn (),
}
const mockSession = {
getEntries : vi.fn (). mockResolvedValue ([]),
getStorage : vi.fn (). mockReturnValue ({ sessionId : 'mock-session-id' }),
}
2026-11-11 16:05:18 +08:00
vi . mocked ( piAgent . createAgentSession ). mockResolvedValue (
mockAgentSession ( mockHarness , mockSession ),
)
2026-07-14 10:25:06 +08:00
const context = {
agent : { id : 'b1' , provider : { name : 'google' }, modelRef : { modelId : 'gemini' } },
dbProviders : [],
teamSkills : [],
allowedDomains : [],
} as unknown as AgentExecutionContext
2026-10-19 15:35:08 +08:00
const taskId = 'test-abort-task'
const abortController = new AbortController ()
2026-07-14 10:25:06 +08:00
2026-10-19 15:35:08 +08:00
await runInLocalTaskContext ({ taskId , abortController }, async () => {
const executionPromise = agentChatActivity ({
taskId ,
teamId : 't1' ,
agentId : 'b1' ,
message : 'Hi' ,
imageUrls : [],
projectId : 'p1' ,
folderId : 'f1' ,
sessionId : 'mock-session-id' ,
context ,
})
// Yield to let the asynchronous setup add the abort event listener
await new Promise (( resolve ) => setTimeout ( resolve , 50 ))
abortController . abort ()
expect ( mockHarness . abort ). toHaveBeenCalled ()
// Resolve the prompt promise to allow the activity to finish clean
resolvePrompt ({
content : [{ type : 'text' , text : 'AI response' }],
usage : { input : 10 , output : 20 },
})
await executionPromise
2026-07-14 10:25:06 +08:00
})
})
2026-11-11 16:05:18 +08:00
it ( 'rejects a failed native answer instead of completing the workflow' , async () => {
2026-06-03 11:46:24 +08:00
const mockHarness = {
2026-07-23 11:11:48 +08:00
subscribe : vi.fn (),
2026-06-03 11:46:24 +08:00
prompt : vi.fn (). mockResolvedValue ({
content : [],
usage : { input : 0 , output : 0 },
stopReason : 'error' ,
errorMessage : 'API key not valid' ,
}),
}
const mockSession = {
getEntries : vi.fn (). mockResolvedValue ([]),
getStorage : vi.fn (). mockReturnValue ({ sessionId : 'mock-session-id' }),
}
2026-11-11 16:05:18 +08:00
vi . mocked ( piAgent . createAgentSession ). mockResolvedValue (
mockAgentSession ( mockHarness , mockSession ),
)
2026-06-03 11:46:24 +08:00
const context = {
agent : { id : 'b1' , provider : { name : 'google' }, modelRef : { modelId : 'gemini' } },
dbProviders : [],
teamSkills : [],
allowedDomains : [],
} as unknown as AgentExecutionContext
2026-11-11 16:05:18 +08:00
await expect (
agentChatActivity ({
teamId : 't1' ,
agentId : 'b1' ,
message : 'Hi' ,
imageUrls : [],
projectId : 'p1' ,
folderId : 'f1' ,
sessionId : 'mock-session-id' ,
context ,
}),
). rejects . toThrow ( 'API key not valid' )
2026-06-03 11:46:24 +08:00
})
2026-06-22 09:58:35 +08:00
it ( 'should pass thinkingLevel from agent config to createAgentSession' , async () => {
const mockHarness = {
2026-07-23 11:11:48 +08:00
subscribe : vi.fn (),
2026-06-22 09:58:35 +08:00
prompt : vi.fn (). mockResolvedValue ({
content : [],
usage : { input : 0 , output : 0 },
}),
getThinkingLevel : vi.fn (). mockReturnValue ( 'high' ),
}
const mockSession = {
getEntries : vi.fn (). mockResolvedValue ([]),
getStorage : vi.fn (). mockReturnValue ({ sessionId : 'mock-session-id' }),
}
2026-11-11 16:05:18 +08:00
vi . mocked ( piAgent . createAgentSession ). mockResolvedValue (
mockAgentSession ( mockHarness , mockSession ),
)
2026-06-22 09:58:35 +08:00
const context = {
agent : {
id : 'b1' ,
provider : { name : 'google' },
modelRef : { modelId : 'gemini' },
config : { thinkingLevel : 'high' },
},
dbProviders : [],
teamSkills : [],
allowedDomains : [],
} as unknown as AgentExecutionContext
await agentChatActivity ({
teamId : 't1' ,
agentId : 'b1' ,
message : 'Hi' ,
imageUrls : [],
projectId : 'p1' ,
folderId : 'f1' ,
sessionId : 'mock-session-id' ,
context ,
})
expect ( piAgent . createAgentSession ). toHaveBeenCalledWith (
expect . objectContaining ({
thinkingLevel : 'high' ,
}),
)
})
2026-05-27 23:40:14 +08:00
it ( 'should call autofillAiActivity and run autofill tool' , async () => {
const mockHarness = {
2026-07-23 11:11:48 +08:00
subscribe : vi.fn (),
2026-05-27 23:40:14 +08:00
prompt : vi.fn (). mockResolvedValue ({
content : [{ type : 'text' , text : 'Captured' }],
usage : { input : 5 , output : 5 },
}),
}
const mockSession = {
getEntries : vi.fn (). mockResolvedValue ([]),
getStorage : vi.fn (). mockReturnValue ({ sessionId : 'mock-session-id' }),
}
2026-05-28 11:43:42 +08:00
vi . mocked ( piAgent . createAgentSession ). mockImplementation ( async ( config : unknown ) => {
const params = config as {
2026-11-11 16:05:18 +08:00
customTools : ToolRegistration []
2026-05-28 11:43:42 +08:00
}
const tool = params . customTools . find (( t ) => t . name === 'autofill_metadata' )
2026-05-27 23:40:14 +08:00
if ( tool ) {
2026-11-11 16:05:18 +08:00
await invokeTool ( tool , '1' , { f1 : 'val' })
2026-05-27 23:40:14 +08:00
}
2026-11-11 16:05:18 +08:00
return mockAgentSession ( mockHarness , mockSession )
2026-05-27 23:40:14 +08:00
})
const context = {
agent : { id : 'b1' , provider : { name : 'google' }, modelRef : { modelId : 'gemini' } },
dbProviders : [],
teamSkills : [],
allowedDomains : [],
2026-05-28 11:43:42 +08:00
} as unknown as AgentExecutionContext
2026-05-27 23:40:14 +08:00
const res = await autofillAiActivity ({
teamId : 't1' ,
images : [],
fields : [{ id : 'f1' , config : { name : 'F1' , type : 'text' } }],
context ,
})
expect ( res . text ). toBe ( '{"f1":"val"}' )
expect ( res . usage . inputTokens ). toBe ( 5 )
2026-05-19 16:05:09 +08:00
})
2026-08-05 10:33:02 +08:00
2026-08-13 13:41:46 +08:00
it ( 'should use the base autofill prompt without any creation-context injection' , async () => {
2026-08-05 10:33:02 +08:00
const mockHarness = {
subscribe : vi.fn (),
prompt : vi.fn (). mockResolvedValue ({
content : [{ type : 'text' , text : 'Captured' }],
usage : { input : 5 , output : 5 },
}),
}
const mockSession = {
getEntries : vi.fn (). mockResolvedValue ([]),
getStorage : vi.fn (). mockReturnValue ({ sessionId : 'mock-session-id' }),
}
2026-09-08 14:19:03 +08:00
let capturedSystemPrompt = ''
vi . mocked ( piAgent . createAgentSession ). mockImplementation ( async ( config : unknown ) => {
const params = config as {
systemPrompt? : string
2026-11-11 16:05:18 +08:00
customTools : ToolRegistration []
2026-09-08 14:19:03 +08:00
}
capturedSystemPrompt = params . systemPrompt ?? ''
const tool = params . customTools . find (( t ) => t . name === 'autofill_metadata' )
if ( tool ) {
2026-11-11 16:05:18 +08:00
await invokeTool ( tool , '1' , { f1 : 'val' })
2026-09-08 14:19:03 +08:00
}
2026-11-11 16:05:18 +08:00
return mockAgentSession ( mockHarness , mockSession )
2026-09-08 14:19:03 +08:00
})
const context = {
agent : {
id : 'b1' ,
type : 'autofill' ,
provider : { name : 'google' },
modelRef : { modelId : 'gemini' },
},
dbProviders : [],
teamSkills : [],
allowedDomains : [],
} as unknown as AgentExecutionContext
await autofillAiActivity ({
teamId : 't1' ,
assetId : 'a1' ,
assetName : 'test.mp4' ,
mediaType : 'video/mp4' ,
duration : 30.5 ,
images : [],
fields : [{ id : 'f1' , config : { name : 'F1' , type : 'text' } }],
context ,
})
const capturedPrompt = mockHarness . prompt . mock . calls [ 0 ] ? .[ 0 ] ?? ''
expect ( capturedPrompt ). toContain ( 'You are tasked with analyzing the asset "test.mp4"' )
expect ( capturedPrompt ). toContain ( 'Call the "read_asset" tool with assetId: "a1"' )
expect ( capturedPrompt ). toContain (
'Video duration: 30.5s. Recommended inspection: call read_asset with videoConfig: { start: 0, end: 30.5, count: 10 }.' ,
)
expect ( capturedPrompt ). toContain (
'call the "autofill_metadata" tool to provide the extracted metadata values.' ,
)
expect ( capturedPrompt ). toContain (
'If "read_asset" fails or returns an error, do not autofill any metadata and report to the user directly. Do not try anything fancy, for example downloading the file or using python/ffmpeg to extract content.' ,
)
expect ( capturedPrompt ). not . toContain ( '<context>' )
expect ( capturedSystemPrompt ). toContain (
"If 'read_asset' fails or returns an error, do not autofill any metadata and report to the user directly. Do not try anything fancy, for example downloading the file or using python/ffmpeg to extract content." ,
)
})
it ( 'should include PDF page count recommendations in autofill prompt when present' , async () => {
const mockHarness = {
subscribe : vi.fn (),
prompt : vi.fn (). mockResolvedValue ({
content : [{ type : 'text' , text : 'Captured' }],
usage : { input : 5 , output : 5 },
}),
}
const mockSession = {
getEntries : vi.fn (). mockResolvedValue ([]),
getStorage : vi.fn (). mockReturnValue ({ sessionId : 'mock-session-id' }),
}
2026-08-05 10:33:02 +08:00
vi . mocked ( piAgent . createAgentSession ). mockImplementation ( async ( config : unknown ) => {
const params = config as {
2026-11-11 16:05:18 +08:00
customTools : ToolRegistration []
2026-08-05 10:33:02 +08:00
}
const tool = params . customTools . find (( t ) => t . name === 'autofill_metadata' )
if ( tool ) {
2026-11-11 16:05:18 +08:00
await invokeTool ( tool , '1' , { f1 : 'val' })
2026-08-05 10:33:02 +08:00
}
2026-11-11 16:05:18 +08:00
return mockAgentSession ( mockHarness , mockSession )
2026-08-05 10:33:02 +08:00
})
const context = {
agent : { id : 'b1' , provider : { name : 'google' }, modelRef : { modelId : 'gemini' } },
dbProviders : [],
teamSkills : [],
allowedDomains : [],
} as unknown as AgentExecutionContext
await autofillAiActivity ({
teamId : 't1' ,
2026-09-08 14:19:03 +08:00
assetId : 'pdf-1' ,
assetName : 'report.pdf' ,
mediaType : 'application/pdf' ,
pageCount : 15 ,
2026-08-05 10:33:02 +08:00
images : [],
fields : [{ id : 'f1' , config : { name : 'F1' , type : 'text' } }],
context ,
})
const capturedPrompt = mockHarness . prompt . mock . calls [ 0 ] ? .[ 0 ] ?? ''
2026-09-08 14:19:03 +08:00
expect ( capturedPrompt ). toContain ( 'You are tasked with analyzing the asset "report.pdf"' )
expect ( capturedPrompt ). toContain (
'Document pages: 15. Recommended inspection: call read_asset with docConfig: { mode: "pages", startPage: 1, endPage: 15 } or mode: "text".' ,
)
2026-08-05 10:33:02 +08:00
})
2026-09-08 14:52:37 +08:00
it ( 'should ignore inappropriate mediaType recommendations in autofillAiActivity' , async () => {
const mockHarness = {
subscribe : vi.fn (),
prompt : vi.fn (). mockResolvedValue ({
content : [{ type : 'text' , text : 'Captured' }],
usage : { input : 5 , output : 5 },
}),
}
const mockSession = {
getEntries : vi.fn (). mockResolvedValue ([]),
getStorage : vi.fn (). mockReturnValue ({ sessionId : 'mock-session-id' }),
}
vi . mocked ( piAgent . createAgentSession ). mockImplementation ( async ( config : unknown ) => {
const params = config as {
2026-11-11 16:05:18 +08:00
customTools : ToolRegistration []
2026-09-08 14:52:37 +08:00
}
const tool = params . customTools . find (( t ) => t . name === 'autofill_metadata' )
if ( tool ) {
2026-11-11 16:05:18 +08:00
await invokeTool ( tool , '1' , { f1 : 'val' })
2026-09-08 14:52:37 +08:00
}
2026-11-11 16:05:18 +08:00
return mockAgentSession ( mockHarness , mockSession )
2026-09-08 14:52:37 +08:00
})
const context = {
agent : { id : 'b1' , provider : { name : 'google' }, modelRef : { modelId : 'gemini' } },
dbProviders : [],
teamSkills : [],
allowedDomains : [],
} as unknown as AgentExecutionContext
// For a video asset, pageCount should NOT produce Document pages recommendation
await autofillAiActivity ({
teamId : 't1' ,
assetId : 'video-1' ,
assetName : 'video.mp4' ,
mediaType : 'video/mp4' ,
duration : 10.1 ,
pageCount : 300 ,
images : [],
fields : [{ id : 'f1' , config : { name : 'F1' , type : 'text' } }],
context ,
})
const videoPrompt = mockHarness . prompt . mock . calls [ 0 ] ? .[ 0 ] ?? ''
expect ( videoPrompt ). toContain ( 'Video duration: 10.1s' )
expect ( videoPrompt ). not . toContain ( 'Document pages' )
// For a PDF asset, duration should NOT produce Video duration recommendation
await autofillAiActivity ({
teamId : 't1' ,
assetId : 'pdf-2' ,
assetName : 'document.pdf' ,
mediaType : 'application/pdf' ,
duration : 10.1 ,
pageCount : 50 ,
images : [],
fields : [{ id : 'f1' , config : { name : 'F1' , type : 'text' } }],
context ,
})
const pdfPrompt = mockHarness . prompt . mock . calls [ 1 ] ? .[ 0 ] ?? ''
expect ( pdfPrompt ). toContain ( 'Document pages: 50' )
expect ( pdfPrompt ). not . toContain ( 'Video duration' )
2026-10-13 00:03:21 +08:00
// For a 3D asset, should produce 3D Model recommendation
await autofillAiActivity ({
teamId : 't1' ,
assetId : 'model-3' ,
assetName : 'robot.glb' ,
mediaType : 'model/gltf-binary' ,
images : [],
fields : [{ id : 'f1' , config : { name : 'F1' , type : 'text' } }],
context ,
})
const modelPrompt = mockHarness . prompt . mock . calls [ 2 ] ? .[ 0 ] ?? ''
expect ( modelPrompt ). toContain ( '3D Model: This asset has an orthogonal 4-view composite image' )
expect ( modelPrompt ). toContain (
'Front view at top-left, Right side view at top-right, Back view at bottom-left, Left side view at bottom-right' ,
)
2026-09-08 14:52:37 +08:00
})
2026-05-19 16:05:09 +08:00
})
2026-06-03 15:48:25 +08:00
describe ( 'Agent Database Activities Integration' , () => {
setupTestDbHooks ()
2026-08-16 11:16:14 +08:00
// 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 ))
2026-06-03 16:17:25 +08:00
let team : Team
let user : User
let project : Project
let asset : Asset
2026-06-03 15:48:25 +08:00
beforeEach ( async () => {
vi . restoreAllMocks ()
team = await prisma . team . create ({
data : { name : 'Test Team' },
})
user = await prisma . user . create ({
data : {
name : 'Test Human' ,
email : 'human@shumai.ai' ,
type : 'human' ,
},
})
project = await prisma . project . create ({
data : {
name : 'Test Project' ,
teamId : team.id ,
},
})
asset = await prisma . asset . create ({
data : {
name : 'file.png' ,
type : AssetType . file ,
status : AssetStatus.uploaded ,
projectId : project.id ,
},
})
await prisma . teamMember . create ({
data : {
teamId : team.id ,
userId : user.id ,
role : 'owner' ,
scope : 'team' ,
},
})
})
describe ( 'initializeAgentSessionActivity' , () => {
2026-11-11 16:05:18 +08:00
const synchronize = async ( sessionId : string , userCommentId : string ) =>
agentSessionService . withWriter ( sessionId , async ( storage ) => {
const harness = await Harness . open (
storage ,
{ models : createModels (), registry : createRegistry () },
BACKGROUND_CONTEXT ,
)
try {
await commentContext . synchronizeCommentContext ({
conversation : await harness . root ( BACKGROUND_CONTEXT ),
sessionId ,
userCommentId ,
teamId : team.id ,
agentId : 'test-agent-id' ,
})
} finally {
await harness . close ( BACKGROUND_CONTEXT )
}
})
it ( 'copies independent context with authors, mentions, attachments and media positions' , async () => {
await prisma . asset . update ({
where : { id : asset.id },
2026-08-30 15:25:13 +08:00
data : {
2026-11-11 16:05:18 +08:00
media : {
proxyType : '3d' ,
duration : 0 ,
filesize : 0 ,
frames : 0 ,
imageTranscodes : [],
videoTranscodes : [],
finishedAt : '' ,
metadata : null ,
original : null ,
2026-07-29 11:56:11 +08:00
},
2026-07-29 14:59:48 +08:00
},
})
2026-11-11 16:05:18 +08:00
const attachment = await prisma . asset . create ({
2026-10-13 00:03:21 +08:00
data : {
2026-11-11 16:05:18 +08:00
name : 'doc.pdf' ,
2026-10-13 00:03:21 +08:00
type : 'file' ,
2026-11-11 16:05:18 +08:00
status : 'uploaded' ,
mediaType : 'application/pdf' ,
2026-10-13 00:03:21 +08:00
projectId : project.id ,
},
})
2026-11-11 16:05:18 +08:00
const first = await prisma . assetComment . create ({
data : { assetId : asset.id , message : `Hello <@ ${ user . id } >` , creatorId : user.id , second : 1 },
})
await prisma . assetCommentAttachment . create ({
data : { commentId : first.id , assetId : attachment.id },
})
await sleep ( 2 )
const second = await prisma . assetComment . create ({
data : { assetId : asset.id , message : 'Next' , creatorId : user.id },
})
await sleep ( 2 )
const third = await prisma . assetComment . create ({
data : { assetId : asset.id , message : 'Third' , creatorId : user.id },
})
const initialize = async ( id : string ) => {
const sessionId = await initializeAgentSessionActivity ({
teamId : team.id ,
agentId : 'test-agent-id' ,
userCommentId : id ,
userId : user.id ,
})
await synchronize ( sessionId , id )
return sessionId
}
const secondSession = await initialize ( second . id )
const thirdSession = await initialize ( third . id )
expect ( secondSession ). not . toBe ( thirdSession )
const entries = await agentSessionService . getEntries ( secondSession )
const message = entries
. map ( getShumaiMessage )
. find (( data ) => data ? . sourceCommentId === first . id )
expect ( message ). toMatchObject ({
displayText : `Hello <@ ${ user . name } >` ,
context : {
user : { name : user.name , role : 'owner' },
position : { type : 'degree' },
attachedFiles : [{ id : attachment.id , mimeType : 'application/pdf' }],
2026-10-13 00:03:21 +08:00
},
})
2026-11-11 16:05:18 +08:00
expect ( entries . filter (( e ) => e . kind === 'shumai.message' )). toHaveLength ( 1 )
expect (
( await agentSessionService . getEntries ( thirdSession )). filter (
( e ) => e . kind === 'shumai.message' ,
),
). toHaveLength ( 2 )
expect (
await prisma . agentSession . count ({ where : { assetId : asset.id , userCommentId : null } }),
). toBe ( 0 )
expect ( await prisma . agentSessionEntry . count ()). toBe ( 0 )
// Repeated initialization is idempotent, and deleting another session cannot remove copied context.
await initialize ( second . id )
await prisma . agentSession . delete ({ where : { id : thirdSession } })
expect ( await agentSessionService . getEntries ( secondSession )). toEqual ( entries )
})
2026-10-13 00:03:21 +08:00
2026-11-11 16:05:18 +08:00
it ( 'copies thread replies without the triggering comment, placeholders or duplicate agent answers' , async () => {
const root = await prisma . assetComment . create ({
data : { assetId : asset.id , message : 'Question' , creatorId : user.id },
})
await prisma . assetComment . create ({
data : { assetId : asset.id , message : '__CHAT__' , replyToId : root.id },
})
await sleep ( 2 )
const reply = await prisma . assetComment . create ({
data : {
assetId : asset.id ,
message : 'Earlier reply' ,
creatorId : user.id ,
replyToId : root.id ,
},
})
await sleep ( 2 )
const current = await prisma . assetComment . create ({
data : { assetId : asset.id , message : 'Trigger' , creatorId : user.id , replyToId : root.id },
})
2026-10-13 00:03:21 +08:00
const sessionId = await initializeAgentSessionActivity ({
teamId : team.id ,
agentId : 'test-agent-id' ,
2026-11-11 16:05:18 +08:00
userCommentId : current.id ,
2026-10-13 00:03:21 +08:00
userId : user.id ,
})
2026-11-11 16:05:18 +08:00
await synchronize ( sessionId , current . id )
const records = ( await agentSessionService . getEntries ( sessionId ))
. map ( getShumaiMessage )
. filter ( Boolean )
expect ( records . map (( record ) => record ? . sourceCommentId )). toEqual ([ root . id , reply . id ])
expect ( records [ 0 ] ? . context ? . thread ). toEqual ({ id : root.id , replyCount : 2 })
await initializeAgentSessionActivity ({
teamId : team.id ,
agentId : 'test-agent-id' ,
userCommentId : current.id ,
})
await synchronize ( sessionId , current . id )
expect (
( await agentSessionService . getEntries ( sessionId )). map ( getShumaiMessage ). filter ( Boolean ),
). toEqual ( records )
2026-10-13 00:03:21 +08:00
})
2026-07-27 11:24:48 +08:00
it ( 'should return user name and role for team member' , async () => {
const info = await getUserTeamInfoActivity ({
userId : user.id ,
teamId : team.id ,
})
expect ( info ). toBeDefined ()
expect ( info ? . name ). toBe ( user . name )
expect ( info ? . role ). toBe ( 'owner' )
})
2026-06-03 15:48:25 +08:00
})
describe ( 'Comment Operations' , () => {
it ( 'should create, update, and delete comments correctly' , async () => {
const comment = await createCommentActivity ({
assetId : asset.id ,
message : 'Drafting response' ,
agentId : 'default' ,
})
expect ( comment . id ). toBeDefined ()
expect ( comment . message ). toBe ( 'Drafting response' )
const updated = await updateCommentActivity ({
commentId : comment.id ,
message : 'Final response' ,
})
expect ( updated . message ). toBe ( 'Final response' )
await deleteCommentActivity ( comment . id )
const deleted = await prisma . assetComment . findUnique ({ where : { id : comment.id } })
expect ( deleted ). toBeNull ()
})
2026-10-31 12:02:30 +08:00
it ( 'should create comment even if cancelled with DBOSWorkflowCancelledError (runOnCancel: true)' , async () => {
const realCancelErr = new DBOSError . DBOSWorkflowCancelledError ( 'test-workflow-id' )
const isWithinWorkflowSpy = vi . spyOn ( DBOS , 'isWithinWorkflow' ). mockReturnValue ( true )
const runStepSpy = vi . spyOn ( DBOS , 'runStep' ). mockRejectedValue ( realCancelErr )
const comment = await createCommentActivity ({
assetId : asset.id ,
message : 'Autofill failed: workflow cancelled' ,
agentId : 'default' ,
})
expect ( comment . id ). toBeDefined ()
expect ( comment . message ). toBe ( 'Autofill failed: workflow cancelled' )
const savedComment = await prisma . assetComment . findUnique ({ where : { id : comment.id } })
expect ( savedComment ). not . toBeNull ()
expect ( savedComment ? . message ). toBe ( 'Autofill failed: workflow cancelled' )
isWithinWorkflowSpy . mockRestore ()
runStepSpy . mockRestore ()
})
2026-06-03 15:48:25 +08:00
})
describe ( 'Context Retrievals' , () => {
it ( 'should retrieve Agent chat and autofill contexts correctly' , async () => {
const provider = await prisma . provider . create ({
data : {
teamId : team.id ,
name : 'openai' ,
config : {
2026-06-17 16:07:48 +08:00
api : 'openai-completions' ,
2026-06-03 15:48:25 +08:00
apiKey : 'mock-key' ,
},
},
})
const model = await prisma . model . create ({
data : {
providerId : provider.id ,
modelId : 'gpt-4' ,
name : 'GPT 4' ,
config : {
reasoning : false ,
input : [ 'text' ],
contextWindow : 8192 ,
maxTokens : 2048 ,
2026-06-03 16:02:06 +08:00
cost : { input : 0.01 , output : 0.03 , cacheRead : 0 , cacheWrite : 0 },
2026-06-03 15:48:25 +08:00
},
},
})
// Create User to map Agent 1-to-1
const agentUser = await prisma . user . create ({
data : {
id : 'chat-agent-id' ,
name : 'Chat Agent User' ,
email : 'chatagent@shumai.ai' ,
type : 'agent' ,
},
})
2026-08-10 17:33:40 +08:00
// Create two team skills, only one of which is enabled for the agent
const enabledSkill = await prisma . skill . create ({
data : {
name : 'Enabled Chat Skill' ,
assetId : 'asset-enabled' ,
hash : 'enabled-hash' ,
teamId : team.id ,
},
})
const disabledSkill = await prisma . skill . create ({
data : {
name : 'Disabled Chat Skill' ,
assetId : 'asset-disabled' ,
hash : 'disabled-hash' ,
teamId : team.id ,
},
})
2026-06-03 15:48:25 +08:00
const agent = await prisma . agent . create ({
data : {
id : agentUser.id ,
teamId : team.id ,
type : 'chat' ,
providerId : provider.id ,
modelId : model.id ,
config : {
provider : 'openai' ,
model : 'gpt-4' ,
},
2026-08-10 17:33:40 +08:00
skills : {
create : [{ skillId : enabledSkill.id }],
},
2026-06-03 15:48:25 +08:00
},
})
const chatCtx = await getAgentChatContextActivity ({
teamId : team.id ,
agentId : agent.id ,
})
expect ( chatCtx . agent . id ). toBe ( agent . id )
expect ( chatCtx . dbProviders [ 0 ]. name ). toBe ( 'openai' )
2026-08-10 17:33:40 +08:00
// Only the enabled skill must be advertised, and disabled team skills excluded
expect ( chatCtx . teamSkills . map (( s ) => s . id )). toEqual ([ enabledSkill . id ])
expect ( chatCtx . enabledSkillIds ). toEqual ([ enabledSkill . id ])
expect ( chatCtx . teamSkills . map (( s ) => s . id )). not . toContain ( disabledSkill . id )
2026-06-03 15:48:25 +08:00
2026-08-16 11:16:14 +08:00
// 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' )
2026-06-03 15:48:25 +08:00
// Create User for autofill agent
const autofillUser = await prisma . user . create ({
data : {
name : 'Autofill Agent User' ,
email : 'autofillagent@shumai.ai' ,
type : 'agent' ,
},
})
const autofillAgent = await prisma . agent . create ({
data : {
id : autofillUser.id ,
teamId : team.id ,
type : 'autofill' ,
enabled : true ,
providerId : provider.id ,
modelId : model.id ,
config : {
provider : 'openai' ,
model : 'gpt-4' ,
},
2026-08-10 17:33:40 +08:00
skills : {
create : [{ skillId : enabledSkill.id }],
},
2026-06-03 15:48:25 +08:00
},
})
const autofillCtx = await getAgentAutofillContextActivity ({
teamId : team.id ,
})
expect ( autofillCtx . agent . id ). toBe ( autofillAgent . id )
2026-08-10 17:33:40 +08:00
// Only the enabled skill must be advertised for the autofill agent as well
expect ( autofillCtx . teamSkills . map (( s ) => s . id )). toEqual ([ enabledSkill . id ])
expect ( autofillCtx . enabledSkillIds ). toEqual ([ enabledSkill . id ])
expect ( autofillCtx . teamSkills . map (( s ) => s . id )). not . toContain ( disabledSkill . id )
})
it ( 'should return an empty enabled skill list when the agent has no skills enabled' , async () => {
const provider = await prisma . provider . create ({
data : {
teamId : team.id ,
name : 'openai-noskill' ,
config : {
api : 'openai-completions' ,
apiKey : 'mock-key' ,
},
},
})
const model = await prisma . model . create ({
data : {
providerId : provider.id ,
modelId : 'gpt-4' ,
name : 'GPT 4' ,
config : {
reasoning : false ,
input : [ 'text' ],
contextWindow : 8192 ,
maxTokens : 2048 ,
cost : { input : 0.01 , output : 0.03 , cacheRead : 0 , cacheWrite : 0 },
},
},
})
await prisma . skill . create ({
data : {
name : 'Team Wide Skill' ,
assetId : 'asset-team' ,
hash : 'team-hash' ,
teamId : team.id ,
},
})
const agentUser = await prisma . user . create ({
data : {
name : 'No Skill Agent User' ,
email : 'noskillagent@shumai.ai' ,
type : 'agent' ,
},
})
const agent = await prisma . agent . create ({
data : {
id : agentUser.id ,
teamId : team.id ,
type : 'chat' ,
providerId : provider.id ,
modelId : model.id ,
config : {
provider : 'openai-noskill' ,
model : 'gpt-4' ,
},
},
})
const chatCtx = await getAgentChatContextActivity ({
teamId : team.id ,
agentId : agent.id ,
})
// Team-wide skill exists but is not enabled for this agent
expect ( chatCtx . teamSkills ). toEqual ([])
expect ( chatCtx . enabledSkillIds ). toEqual ([])
2026-06-03 15:48:25 +08:00
})
})
describe ( 'Asset and Comment Fetching' , () => {
it ( 'should retrieve asset and comment correctly' , async () => {
const fetchedAsset = await getAssetActivity ( asset . id )
expect ( fetchedAsset ? . id ). toBe ( asset . id )
const comment = await createCommentActivity ({
assetId : asset.id ,
message : 'draft comment' ,
})
const fetchedComment = await getCommentActivity ( comment . id )
expect ( fetchedComment ? . id ). toBe ( comment . id )
})
2026-07-21 15:04:38 +08:00
it ( 'should resolve version stack asset to its latest version file' , async () => {
const stack = await prisma . asset . create ({
data : {
name : 'Stack' ,
type : AssetType . version_stack ,
status : AssetStatus.uploaded ,
projectId : project.id ,
},
})
await prisma . asset . create ({
data : {
name : 'v1.png' ,
type : AssetType . file ,
mediaType : 'image/png' ,
status : AssetStatus.uploaded ,
projectId : project.id ,
parentId : stack.id ,
sortIndex : 'a1' ,
},
})
const v2 = await prisma . asset . create ({
data : {
name : 'v2.png' ,
type : AssetType . file ,
mediaType : 'image/png' ,
status : AssetStatus.uploaded ,
projectId : project.id ,
parentId : stack.id ,
sortIndex : 'a0' ,
},
})
const fetchedAsset = await getAssetActivity ( stack . id )
expect ( fetchedAsset ? . id ). toBe ( v2 . id )
expect ( fetchedAsset ? . name ). toBe ( 'v2.png' )
})
2026-06-03 15:48:25 +08:00
})
describe ( 'getAssetPathContextActivity' , () => {
it ( 'should build correct asset path context from root to asset' , async () => {
const rootFolder = await prisma . asset . create ({
data : {
name : 'RootFolder' ,
type : AssetType . folder ,
status : AssetStatus.uploaded ,
projectId : project.id ,
},
})
const subfolder = await prisma . asset . create ({
data : {
name : 'SubFolder' ,
type : AssetType . folder ,
status : AssetStatus.uploaded ,
projectId : project.id ,
parentId : rootFolder.id ,
},
})
const targetAsset = await prisma . asset . create ({
data : {
name : 'TargetImage.webp' ,
type : AssetType . file ,
status : AssetStatus.uploaded ,
projectId : project.id ,
parentId : subfolder.id ,
},
})
const pathCtx = await getAssetPathContextActivity ( targetAsset . id )
2026-08-30 15:25:13 +08:00
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' },
])
2026-06-03 15:48:25 +08:00
})
})
describe ( 'getProjectAutofillFieldsActivity & updateAssetMetadataActivity' , () => {
it ( 'should get fields and update metadata' , async () => {
// Create team field
await prisma . metadataField . create ({
data : {
key : 'field_key_1' ,
scope : 'TEAM' ,
teamId : team.id ,
2026-08-13 13:41:46 +08:00
config : { name : 'Title Extractor' , type : 'text' , autofillSource : 'CONTENT' },
2026-06-03 15:48:25 +08:00
},
})
const fields = await getProjectAutofillFieldsActivity ( project . id )
expect ( fields . length ). toBe ( 1 )
expect ( fields [ 0 ]. key ). toBe ( 'field_key_1' )
await updateAssetMetadataActivity ({
assetId : asset.id ,
metadata : [{ key : 'field_key_1' , value : 'Hello Web' }],
})
const updatedVal = await prisma . assetMetadataValue . findFirst ({
where : { assetId : asset.id , fieldKey : 'field_key_1' },
})
expect ( updatedVal ? . stringValue ). toBe ( 'Hello Web' )
})
})
2026-07-11 20:54:09 +08:00
describe ( 'generateSessionNameActivity' , () => {
it ( 'should generate and save session name for chat sessions' , async () => {
await prisma . team . create ({
data : { id : 't1' , name : 'Test Team' },
})
const user = await prisma . user . create ({
data : { id : 'u1' , name : 'Test User' , email : 'u1@test.com' },
})
const agentUser = await prisma . user . create ({
data : {
id : 'agent-123' ,
name : 'Chat Agent User' ,
email : 'agent@shumai.ai' ,
type : 'agent' ,
},
})
const agent = await prisma . agent . create ({
data : {
id : agentUser.id ,
teamId : 't1' ,
type : 'chat' ,
config : { provider : 'openai' , model : 'gpt-4' },
},
})
await prisma . agentSession . create ({
data : {
id : 'session-123' ,
agentId : 'agent-123' ,
userId : user.id ,
cwd : process.cwd (),
type : 'chat' ,
name : null ,
},
})
const mockHarness = {
2026-07-23 11:11:48 +08:00
subscribe : vi.fn (),
2026-07-11 20:54:09 +08:00
prompt : vi.fn (). mockResolvedValue ({
content : [{ type : 'text' , text : ' "Summarized Chat Title" ' }],
}),
}
2026-11-11 16:05:18 +08:00
vi . mocked ( piAgent . createAgentSession ). mockResolvedValue ( mockAgentSession ( mockHarness , {}))
2026-07-11 20:54:09 +08:00
await generateSessionNameActivity ({
teamId : 't1' ,
agentId : 'agent-123' ,
prompt : 'hello world prompt' ,
sessionId : 'session-123' ,
context : {
agent : {
... agent ,
provider : { name : 'openai' },
modelRef : {
id : 'm1' ,
providerName : 'openai' ,
modelId : 'gpt-4' ,
name : 'GPT-4' ,
config : {},
createdAt : new Date (),
updatedAt : new Date (),
},
} as unknown as GenerateSessionNameParams [ 'context' ][ 'agent' ],
dbProviders : [
{
name : 'openai' ,
config : { api : 'openai-responses' , apiKey : 'fake-key' },
models : [
{
modelId : 'gpt-4' ,
name : 'GPT-4' ,
config : {
reasoning : false ,
input : [ 'text' ],
contextWindow : 4096 ,
maxTokens : 4096 ,
cost : { input : 0 , output : 0 , cacheRead : 0 , cacheWrite : 0 },
},
},
],
},
],
},
})
2026-07-29 16:31:24 +08:00
expect ( piAgent . createAgentSession ). toHaveBeenCalledWith (
expect . objectContaining ({
disableTools : true ,
}),
)
2026-07-11 20:54:09 +08:00
const updatedSession = await prisma . agentSession . findUnique ({
where : { id : 'session-123' },
})
expect ( updatedSession ? . name ). toBe ( 'Summarized Chat Title' )
2026-07-29 16:31:24 +08:00
expect ( mockHarness . prompt ). toHaveBeenCalledWith (
'Generate a short 2 to 4 word title for a session starting with this message:\n\n<user_message>\nhello world prompt\n</user_message>' ,
2026-11-11 16:05:18 +08:00
{ images : [] },
2026-07-29 16:31:24 +08:00
)
2026-07-11 20:54:09 +08:00
// Verify that transient naming session was cleaned up (deleted)
const namingSessions = await prisma . agentSession . findMany ({
where : { type : 'naming' },
})
expect ( namingSessions ). toHaveLength ( 0 )
})
it ( 'should skip name generation for comment sessions or if name is already set' , async () => {
await prisma . team . create ({
data : { id : 't1' , name : 'Test Team' },
})
const user = await prisma . user . create ({
data : { id : 'u1' , name : 'Test User' , email : 'u1@test.com' },
})
const agentUser = await prisma . user . create ({
data : {
id : 'agent-123' ,
name : 'Chat Agent User' ,
email : 'agent2@shumai.ai' ,
type : 'agent' ,
},
})
await prisma . agent . create ({
data : {
id : agentUser.id ,
teamId : 't1' ,
type : 'chat' ,
config : { provider : 'openai' , model : 'gpt-4' },
},
})
await prisma . agentSession . create ({
data : {
id : 'session-comment' ,
agentId : 'agent-123' ,
userId : user.id ,
cwd : process.cwd (),
type : 'comment' ,
name : null ,
},
})
await prisma . agentSession . create ({
data : {
id : 'session-named' ,
agentId : 'agent-123' ,
userId : user.id ,
cwd : process.cwd (),
type : 'chat' ,
name : 'Existing Name' ,
},
})
vi . mocked ( piAgent . createAgentSession ). mockClear ()
await generateSessionNameActivity ({
teamId : 't1' ,
agentId : 'agent-123' ,
prompt : 'hello comment' ,
sessionId : 'session-comment' ,
context : {
agent : {} as unknown as GenerateSessionNameParams [ 'context' ][ 'agent' ],
dbProviders : [],
},
})
await generateSessionNameActivity ({
teamId : 't1' ,
agentId : 'agent-123' ,
prompt : 'hello named' ,
sessionId : 'session-named' ,
context : {
agent : {} as unknown as GenerateSessionNameParams [ 'context' ][ 'agent' ],
dbProviders : [],
},
})
expect ( piAgent . createAgentSession ). not . toHaveBeenCalled ()
})
2026-09-08 10:47:36 +08:00
it ( 'should log error and not update session name when LLM returns an error' , async () => {
const errorSpy = vi . spyOn ( logger , 'error' )
await prisma . team . create ({
data : { id : 't1' , name : 'Test Team' },
})
const user = await prisma . user . create ({
data : { id : 'u1' , name : 'Test User' , email : 'u1@test.com' },
})
const agentUser = await prisma . user . create ({
data : {
id : 'agent-123' ,
name : 'Chat Agent User' ,
email : 'agent@shumai.ai' ,
type : 'agent' ,
},
})
const agent = await prisma . agent . create ({
data : {
id : agentUser.id ,
teamId : 't1' ,
type : 'chat' ,
config : { provider : 'openai' , model : 'gpt-4' },
},
})
await prisma . agentSession . create ({
data : {
id : 'session-err' ,
agentId : 'agent-123' ,
userId : user.id ,
cwd : process.cwd (),
type : 'chat' ,
name : null ,
},
})
const mockHarness = {
subscribe : vi.fn (),
prompt : vi.fn (). mockResolvedValue ({
content : [{ type : 'text' , text : '' }],
stopReason : 'error' ,
errorMessage : 'Rate limit exceeded (429)' ,
}),
}
2026-11-11 16:05:18 +08:00
vi . mocked ( piAgent . createAgentSession ). mockResolvedValue ( mockAgentSession ( mockHarness , {}))
2026-09-08 10:47:36 +08:00
await generateSessionNameActivity ({
teamId : 't1' ,
agentId : 'agent-123' ,
prompt : 'hello error' ,
sessionId : 'session-err' ,
context : {
agent : {
... agent ,
provider : { name : 'openai' },
modelRef : {
id : 'm1' ,
providerName : 'openai' ,
modelId : 'gpt-4' ,
name : 'GPT-4' ,
config : {},
createdAt : new Date (),
updatedAt : new Date (),
},
} as unknown as GenerateSessionNameParams [ 'context' ][ 'agent' ],
dbProviders : [
{
name : 'openai' ,
config : { api : 'openai-responses' , apiKey : 'fake-key' },
models : [],
},
],
},
})
expect ( errorSpy ). toHaveBeenCalledWith (
expect . objectContaining ({
sessionId : 'session-err' ,
stopReason : 'error' ,
errorMessage : 'Rate limit exceeded (429)' ,
}),
'Failed to generate session name: LLM returned an error' ,
)
const sessionAfter = await prisma . agentSession . findUnique ({
where : { id : 'session-err' },
})
expect ( sessionAfter ? . name ). toBeNull ()
errorSpy . mockRestore ()
})
2026-09-08 11:15:26 +08:00
it ( 'should pass thinkingLevel from agent.config to createAgentSession' , async () => {
await prisma . team . create ({
data : { id : 't-thinking' , name : 'Thinking Team' },
})
const user = await prisma . user . create ({
data : { id : 'u-thinking' , name : 'Thinking User' , email : 'u-thinking@test.com' },
})
const agentUser = await prisma . user . create ({
data : {
id : 'agent-thinking' ,
name : 'Thinking Agent User' ,
email : 'agent-thinking@shumai.ai' ,
type : 'agent' ,
},
})
const agent = await prisma . agent . create ({
data : {
id : agentUser.id ,
teamId : 't-thinking' ,
type : 'chat' ,
config : { provider : 'openai' , model : 'gpt-4' , thinkingLevel : 'low' },
},
})
await prisma . agentSession . create ({
data : {
id : 'session-thinking' ,
agentId : agent.id ,
userId : user.id ,
cwd : process.cwd (),
type : 'chat' ,
name : null ,
},
})
const mockHarness = {
subscribe : vi.fn (),
prompt : vi.fn (). mockResolvedValue ({
content : [{ type : 'text' , text : 'Thinking Title' }],
}),
}
2026-11-11 16:05:18 +08:00
vi . mocked ( piAgent . createAgentSession ). mockResolvedValue ( mockAgentSession ( mockHarness , {}))
2026-09-08 11:15:26 +08:00
await generateSessionNameActivity ({
teamId : 't-thinking' ,
agentId : agent.id ,
prompt : 'test prompt' ,
sessionId : 'session-thinking' ,
context : {
agent : {
... agent ,
provider : { name : 'openai' },
modelRef : {
id : 'm1' ,
providerName : 'openai' ,
modelId : 'gpt-4' ,
name : 'GPT-4' ,
config : {},
createdAt : new Date (),
updatedAt : new Date (),
},
} as unknown as GenerateSessionNameParams [ 'context' ][ 'agent' ],
dbProviders : [
{
name : 'openai' ,
config : { api : 'openai-responses' , apiKey : 'fake-key' },
models : [],
},
],
},
})
expect ( piAgent . createAgentSession ). toHaveBeenCalledWith (
expect . objectContaining ({
thinkingLevel : 'low' ,
disableTools : true ,
}),
)
})
2026-07-11 20:54:09 +08:00
})
2026-08-15 10:25:46 +08:00
describe ( 'Nested AGENTS.md prompt injection' , () => {
2026-11-11 16:05:18 +08:00
beforeEach (() => {
vi . spyOn ( commentContext , 'synchronizeCommentContext' ). mockResolvedValue ()
})
2026-08-15 10:25:46 +08:00
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' }),
}
2026-11-11 16:05:18 +08:00
vi . mocked ( piAgent . createAgentSession ). mockResolvedValue (
mockAgentSession ( mockHarness , mockSession ),
)
2026-08-15 10:25:46 +08:00
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>' ,
)
})
2026-09-01 17:42:56 +08:00
it ( 'agentChatActivity injects # Comment Threads into systemPrompt when userCommentId is present' , async () => {
const user = await prisma . user . create ({
data : { name : 'User_Comment_Prompt' , email : `comment-prompt- ${ Date . now () } @example.com` },
})
const team = await prisma . team . create ({
data : { name : 'Team_Comment_Prompt_' + Date . now () },
})
const project = await prisma . project . create ({
data : { name : 'Project_Comment_Prompt' , teamId : team.id },
})
const asset = await prisma . asset . create ({
data : {
name : 'Asset_1' ,
type : AssetType . file ,
projectId : project.id ,
status : AssetStatus.uploaded ,
},
})
const comment = await prisma . assetComment . create ({
data : {
assetId : asset.id ,
message : 'Question' ,
creatorId : user.id ,
},
})
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' }),
}
2026-11-11 16:05:18 +08:00
vi . mocked ( piAgent . createAgentSession ). mockResolvedValue (
mockAgentSession ( mockHarness , mockSession ),
)
2026-09-01 17:42:56 +08:00
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 : asset.id ,
assetId : asset.id ,
sessionId : 'mock-session-id' ,
userCommentId : comment.id ,
userId : user.id ,
context ,
})
const lastCall = vi . mocked ( piAgent . createAgentSession ). mock . calls . at ( - 1 )
const systemPromptArg = lastCall ? .[ 0 ]. systemPrompt as string
expect ( systemPromptArg ). toContain ( '# Comment Threads' )
expect ( systemPromptArg ). toContain ( '<thread id="..." reply_count="..." />' )
expect ( systemPromptArg ). toContain ( 'read_thread' )
})
2026-10-13 00:03:21 +08:00
it ( 'agentChatActivity injects # 3D Model Inspection into systemPrompt' , async () => {
const user = await prisma . user . create ({
data : { name : 'User_3d_Prompt' , email : `prompt-3d- ${ Date . now () } @example.com` },
})
const team = await prisma . team . create ({
data : { name : 'Team_3d_Prompt_' + Date . now () },
})
const project = await prisma . project . create ({
data : { name : 'Project_3d_Prompt' , teamId : team.id },
})
const asset = await prisma . asset . create ({
data : {
name : 'robot.glb' ,
type : 'file' ,
status : 'processed' ,
mediaType : 'model/gltf-binary' ,
2026-11-11 16:05:18 +08:00
media : {
proxyType : '3d' ,
duration : 0 ,
filesize : 0 ,
frames : 0 ,
imageTranscodes : [],
videoTranscodes : [],
finishedAt : '' ,
metadata : null ,
original : null ,
} as unknown as PrismaJson . MediaInfo ,
2026-10-13 00:03:21 +08:00
projectId : project.id ,
},
})
const comment = await prisma . assetComment . create ({
data : {
assetId : asset.id ,
creatorId : user.id ,
message : 'Check this 3d model' ,
},
})
const mockSession = {
id : 'mock-session-id' ,
subscribe : vi.fn (),
getEntries : vi.fn (). mockResolvedValue ([]),
getStorage : vi.fn (). mockReturnValue ({ sessionId : 'mock-session-id' }),
}
const mockHarness = {
subscribe : vi.fn (),
prompt : vi.fn (). mockResolvedValue ({
content : [{ type : 'text' , text : 'Response' }],
usage : { input : 10 , output : 20 },
}),
}
2026-11-11 16:05:18 +08:00
vi . mocked ( piAgent . createAgentSession ). mockResolvedValue (
mockAgentSession ( mockHarness , mockSession ),
)
2026-10-13 00:03:21 +08:00
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 : asset.id ,
assetId : asset.id ,
sessionId : 'mock-session-id' ,
userCommentId : comment.id ,
userId : user.id ,
context ,
})
const lastCall = vi . mocked ( piAgent . createAgentSession ). mock . calls . at ( - 1 )
const systemPromptArg = lastCall ? .[ 0 ]. systemPrompt as string
expect ( systemPromptArg ). toContain ( '# 3D Model Inspection' )
expect ( systemPromptArg ). toContain ( 'media_type="3d"' )
expect ( systemPromptArg ). toContain ( 'config3d' )
expect ( systemPromptArg ). toContain ( '<position type="degree" degree="..." />' )
})
2026-08-15 10:25:46 +08:00
})
2026-06-03 15:48:25 +08:00
})