mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-27 03:14:11 +00:00
refactor(agent)!: migrate to Pi Durable and embed the agent queue (#525)
* refactor(agent)!: migrate sessions to Pi Durable Replace patched AgentHarness storage with per-session SQLite and PostgreSQL commit mirroring. Migrate legacy history automatically and run agent queues with the main server. BREAKING CHANGE: Remove standalone agent workers and return native Pi entry records from chat history APIs. * fix(agent): constrain session log dialog scrolling Keep the header visible and wrap long output while log entries and expanded records scroll within the dialog. Cover desktop and narrow viewports through the dashboard Sessions flow. * fix(agent): hide entry IDs from session log card headers Retain internal entry IDs in expanded raw records for debugging. Verify that card headers omit the IDs while raw JSON preserves them. * test(e2e): handle browser wheel limits in session log checks Verify that a normal wheel event moves the viewport before explicitly scrolling to the final record. Keep the dialog bounds, fixed header, wrapping, and expanded-record assertions. * fix(agent): select model providers without inheriting unrelated auth * fix(webui): prevent resize feedback when toggling agent panel * test(agent): reproduce concurrent comment session races * fix(agent): serialize comment sessions and deduplicate history * docs(changelog): consolidate Pi Durable changes into one entry
This commit is contained in:
@@ -1,11 +1,11 @@
|
||||
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'
|
||||
import { initAgentWorkflows } from '@shumai/agent'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { workflowService, TaskQueueAgent, TaskQueueTranscode } from '@shumai/workflow-core'
|
||||
import { initAgentWorkflows } from '@shumai/agent'
|
||||
import { initTranscodeWorkflows } from '@shumai/transcode'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { AgentHarness } from '@earendil-works/pi-agent-core'
|
||||
import { TaskQueueAgent, TaskQueueTranscode, workflowService } from '@shumai/workflow-core'
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
|
||||
import { mockModelPrompt, type ModelScenario } from './model-mock'
|
||||
|
||||
describe('Workflow E2E - agentAutofillMedia', () => {
|
||||
setupTestDbHooks()
|
||||
@@ -19,10 +19,7 @@ describe('Workflow E2E - agentAutofillMedia', () => {
|
||||
initTranscodeWorkflows()
|
||||
|
||||
// Spy on the harness prompt method to intercept the LLM call while running real activities & tools
|
||||
vi.spyOn(AgentHarness.prototype, 'prompt').mockImplementation(async function (
|
||||
this: AgentHarness,
|
||||
...args: unknown[]
|
||||
) {
|
||||
mockModelPrompt(async function (this: ModelScenario, ...args: unknown[]) {
|
||||
// Find the real tools configured on the harness
|
||||
const tools = this.getTools()
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Tool execution mock for E2E harness test
|
||||
@@ -411,9 +408,9 @@ describe('Workflow E2E - agentAutofillMedia', () => {
|
||||
})
|
||||
|
||||
// Mock prompt to fail
|
||||
vi.spyOn(AgentHarness.prototype, 'prompt').mockRejectedValueOnce(
|
||||
new Error('LLM rate limit reached'),
|
||||
)
|
||||
mockModelPrompt(async () => {
|
||||
throw new Error('LLM rate limit reached')
|
||||
})
|
||||
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { workflowService, TaskQueueAgent } from '@shumai/workflow-core'
|
||||
import type { AssistantMessage } from '@earendil-works/pi-ai'
|
||||
import { initAgentWorkflows } from '@shumai/agent'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { AgentHarness } from '@earendil-works/pi-agent-core'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { TaskQueueAgent, workflowService } from '@shumai/workflow-core'
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
|
||||
import { mockModelPrompt } from './model-mock'
|
||||
|
||||
describe('Workflow E2E - agentChat', () => {
|
||||
setupTestDbHooks()
|
||||
@@ -15,11 +16,14 @@ describe('Workflow E2E - agentChat', () => {
|
||||
|
||||
initAgentWorkflows()
|
||||
|
||||
vi.spyOn(AgentHarness.prototype, 'prompt').mockResolvedValue({
|
||||
content: [{ type: 'text', text: 'E2E Agent Chat Response Success' }],
|
||||
usage: { input: 10, output: 20 },
|
||||
stopReason: 'stop',
|
||||
} as unknown as Awaited<ReturnType<typeof AgentHarness.prototype.prompt>>)
|
||||
mockModelPrompt(
|
||||
async () =>
|
||||
({
|
||||
content: [{ type: 'text', text: 'E2E Agent Chat Response Success' }],
|
||||
usage: { input: 10, output: 20 },
|
||||
stopReason: 'stop',
|
||||
}) as unknown as AssistantMessage,
|
||||
)
|
||||
|
||||
await workflowService.startWorkers(TaskQueueAgent)
|
||||
})
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
import { closeAgentSessions, initAgentWorkflows } from '@shumai/agent'
|
||||
import { agentSessionService } from '@shumai/core/src/agent/session-service'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { getShumaiMessage } from '@shumai/dtos'
|
||||
import { TaskQueueAgent, workflowService } from '@shumai/workflow-core'
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { mockModelPrompt } from './model-mock'
|
||||
|
||||
describe('Workflow E2E - concurrent agent mentions', () => {
|
||||
setupTestDbHooks()
|
||||
let model: ReturnType<typeof mockModelPrompt>
|
||||
|
||||
beforeAll(async () => {
|
||||
vi.stubEnv('CONCURRENCY_AGENT', '5')
|
||||
initAgentWorkflows()
|
||||
model = mockModelPrompt(async (prompt) => ({
|
||||
content: [{ type: 'text', text: `Reply to ${prompt.split('\n')[0]}` }],
|
||||
}))
|
||||
await workflowService.startWorkers(TaskQueueAgent)
|
||||
})
|
||||
|
||||
beforeEach(() => {
|
||||
model.mockClear()
|
||||
})
|
||||
|
||||
afterAll(async () => {
|
||||
await workflowService.shutdownWorkers()
|
||||
workflowService.close()
|
||||
await closeAgentSessions()
|
||||
vi.restoreAllMocks()
|
||||
vi.unstubAllEnvs()
|
||||
})
|
||||
|
||||
it.each(['new', 'existing'] as const)(
|
||||
'keeps five mentions in one %s thread session with each source comment recorded once',
|
||||
async (kind) => {
|
||||
const team = await prisma.team.create({ data: { name: 'Mention concurrency team' } })
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'Mention concurrency project', teamId: team.id },
|
||||
})
|
||||
const users = await Promise.all(
|
||||
Array.from({ length: 5 }, (_, index) =>
|
||||
prisma.user.create({
|
||||
data: { name: `Mention user ${index}`, email: `mention-${index}@example.test` },
|
||||
}),
|
||||
),
|
||||
)
|
||||
await prisma.teamMember.createMany({
|
||||
data: users.map((user) => ({ teamId: team.id, userId: user.id, role: 'owner' })),
|
||||
})
|
||||
const agentUser = await prisma.user.create({
|
||||
data: { name: 'Mention agent', email: 'mention-agent@example.test', type: 'agent' },
|
||||
})
|
||||
const provider = await prisma.provider.create({
|
||||
data: {
|
||||
teamId: team.id,
|
||||
name: 'google',
|
||||
config: { api: 'google-generative-ai', apiKey: 'unused-test-key' },
|
||||
},
|
||||
})
|
||||
const modelRecord = await prisma.model.create({
|
||||
data: {
|
||||
providerId: provider.id,
|
||||
modelId: 'gemini-test',
|
||||
config: {
|
||||
input: ['text'],
|
||||
reasoning: false,
|
||||
contextWindow: 8192,
|
||||
maxTokens: 1024,
|
||||
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
||||
},
|
||||
},
|
||||
})
|
||||
const agent = await prisma.agent.create({
|
||||
data: {
|
||||
id: agentUser.id,
|
||||
teamId: team.id,
|
||||
type: 'chat',
|
||||
providerId: provider.id,
|
||||
modelId: modelRecord.id,
|
||||
config: { provider: 'google', model: 'gemini-test' },
|
||||
},
|
||||
})
|
||||
const asset = await prisma.asset.create({
|
||||
data: { name: 'comments.txt', type: 'file', projectId: project.id, status: 'processed' },
|
||||
})
|
||||
const root = await assetService.createComment({
|
||||
assetId: asset.id,
|
||||
userId: users[0].id,
|
||||
message: 'Discuss this asset.',
|
||||
attachmentIds: [],
|
||||
})
|
||||
const note = await assetService.createComment({
|
||||
assetId: asset.id,
|
||||
userId: users[0].id,
|
||||
replyToId: root.id,
|
||||
message: 'An ordinary review note.',
|
||||
attachmentIds: [],
|
||||
})
|
||||
const post = (userId: string, message: string) =>
|
||||
assetService.createComment({
|
||||
assetId: asset.id,
|
||||
userId,
|
||||
replyToId: root.id,
|
||||
message: `<@${agent.id}> ${message}`,
|
||||
attachmentIds: [],
|
||||
})
|
||||
const expected = []
|
||||
if (kind === 'existing') {
|
||||
expected.push(await post(users[0].id, 'Establish this thread'))
|
||||
const initialTask = await prisma.workflowTask.findFirstOrThrow({
|
||||
where: { assetId: asset.id, type: 'chat' },
|
||||
})
|
||||
await workflowService.executeWait(initialTask, 45000)
|
||||
}
|
||||
const mentions = await Promise.all(
|
||||
users.map((user, index) => post(user.id, `Request ${index}`)),
|
||||
)
|
||||
expected.push(...mentions)
|
||||
const tasks = await prisma.workflowTask.findMany({
|
||||
where: { assetId: asset.id, type: 'chat' },
|
||||
orderBy: { id: 'desc' },
|
||||
})
|
||||
expect(tasks).toHaveLength(expected.length)
|
||||
const completed = await Promise.all(
|
||||
tasks.map((task) => workflowService.executeWait(task, 45000)),
|
||||
)
|
||||
expect(completed.every((task) => task.status === 'completed')).toBe(true)
|
||||
const sessions = await prisma.agentSession.findMany({
|
||||
where: { agentId: agent.id, assetId: asset.id, userCommentId: root.id, type: 'comment' },
|
||||
})
|
||||
expect(sessions).toHaveLength(1)
|
||||
expect(new Set(completed.map((task) => task.output?.sessionId))).toEqual(
|
||||
new Set([sessions[0].id]),
|
||||
)
|
||||
const entries = await agentSessionService.getEntries(sessions[0].id)
|
||||
const sources = entries.map(getShumaiMessage).filter((message) => message !== undefined)
|
||||
for (const comment of [root, note, ...expected]) {
|
||||
expect(sources.filter((message) => message.sourceCommentId === comment.id)).toHaveLength(1)
|
||||
}
|
||||
for (const mention of mentions) {
|
||||
expect(
|
||||
sources.find((message) => message.sourceCommentId === mention.id)?.context.user?.id,
|
||||
).toBe(mention.creator.id)
|
||||
}
|
||||
const replies = await prisma.assetComment.findMany({
|
||||
where: {
|
||||
assetId: asset.id,
|
||||
replyToId: root.id,
|
||||
creatorId: agent.id,
|
||||
sessionId: sessions[0].id,
|
||||
},
|
||||
})
|
||||
expect(replies).toHaveLength(expected.length)
|
||||
for (let index = 0; index < 5; index++)
|
||||
expect(replies.filter((reply) => reply.message?.includes(`Request ${index}`))).toHaveLength(
|
||||
1,
|
||||
)
|
||||
expect(replies.some((reply) => reply.message === '__CHAT__')).toBe(false)
|
||||
expect(model).toHaveBeenCalledTimes(expected.length)
|
||||
const commits = await prisma.agentSessionCommit.findMany({
|
||||
where: { sessionId: sessions[0].id },
|
||||
orderBy: { seq: 'asc' },
|
||||
})
|
||||
expect(commits.every((commit, index) => commit.seq === BigInt(index + 1))).toBe(true)
|
||||
await closeAgentSessions()
|
||||
expect(await agentSessionService.getEntries(sessions[0].id)).toEqual(entries)
|
||||
},
|
||||
60000,
|
||||
)
|
||||
})
|
||||
@@ -1,12 +1,13 @@
|
||||
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { workflowService, TaskQueueAgent } from '@shumai/workflow-core'
|
||||
import type { AssistantMessage } from '@earendil-works/pi-ai'
|
||||
import { initAgentWorkflows } from '@shumai/agent'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { metadataService } from '@shumai/core/src/metadata/metadata'
|
||||
import { projectService } from '@shumai/core/src/project/project'
|
||||
import { AgentHarness } from '@earendil-works/pi-agent-core'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { TaskQueueAgent, workflowService } from '@shumai/workflow-core'
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
|
||||
import { mockModelPrompt, type ModelScenario } from './model-mock'
|
||||
|
||||
type ToolResult = { content: Array<{ type: string; text?: string }> }
|
||||
type ExecutableTool = {
|
||||
@@ -36,7 +37,7 @@ describe('Workflow E2E - agent Operation tools', () => {
|
||||
content: [{ type: 'text', text }],
|
||||
usage: { input: 10, output: 20 },
|
||||
stopReason: 'stop',
|
||||
}) as unknown as Awaited<ReturnType<typeof AgentHarness.prototype.prompt>>
|
||||
}) as unknown as AssistantMessage
|
||||
|
||||
beforeAll(async () => {
|
||||
process.env.S3_BUCKET = 'shumai-e2e-test-bucket-agent-ops'
|
||||
@@ -44,9 +45,7 @@ describe('Workflow E2E - agent Operation tools', () => {
|
||||
|
||||
initAgentWorkflows()
|
||||
|
||||
vi.spyOn(AgentHarness.prototype, 'prompt').mockImplementation(async function (
|
||||
this: AgentHarness,
|
||||
) {
|
||||
mockModelPrompt(async function (this: ModelScenario) {
|
||||
const tool = (name: string) =>
|
||||
this.getTools().find((t) => t.name === name) as unknown as ExecutableTool | undefined
|
||||
const call = async (name: string, params: Record<string, unknown>) => {
|
||||
|
||||
@@ -1,16 +1,17 @@
|
||||
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { workflowService, TaskQueueAgent } from '@shumai/workflow-core'
|
||||
import type { AssistantMessage } from '@earendil-works/pi-ai'
|
||||
import { initAgentWorkflows } from '@shumai/agent'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { mcpService } from '@shumai/core/src/mcp/mcp-service'
|
||||
import {
|
||||
startTestMcpServer,
|
||||
standardTestTools,
|
||||
startTestMcpServer,
|
||||
type RunningTestMcpServer,
|
||||
} from '@shumai/core/src/mcp/mcp-test-server'
|
||||
import { AgentHarness } from '@earendil-works/pi-agent-core'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { TaskQueueAgent, workflowService } from '@shumai/workflow-core'
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
|
||||
import { mockModelPrompt, type ModelScenario } from './model-mock'
|
||||
|
||||
describe('Workflow E2E - MCP tools', () => {
|
||||
setupTestDbHooks()
|
||||
@@ -36,9 +37,7 @@ describe('Workflow E2E - MCP tools', () => {
|
||||
// proxy tool on the harness and executes it against the real MCP server,
|
||||
// so the full createAgentSession → buildAgentTools → proxy execute →
|
||||
// callMcpTool → MCP server path is exercised.
|
||||
vi.spyOn(AgentHarness.prototype, 'prompt').mockImplementation(async function (
|
||||
this: AgentHarness,
|
||||
) {
|
||||
mockModelPrompt(async function (this: ModelScenario) {
|
||||
const tools = this.getTools()
|
||||
const mcpTool = tools.find((t) => t.name === 'mcp')
|
||||
if (!mcpTool) {
|
||||
@@ -46,7 +45,7 @@ describe('Workflow E2E - MCP tools', () => {
|
||||
content: [{ type: 'text', text: 'NO_MCP_TOOL' }],
|
||||
usage: { input: 10, output: 20 },
|
||||
stopReason: 'stop',
|
||||
} as unknown as Awaited<ReturnType<typeof AgentHarness.prototype.prompt>>
|
||||
} as unknown as AssistantMessage
|
||||
}
|
||||
const result = await (
|
||||
mcpTool.execute as unknown as (
|
||||
@@ -65,7 +64,7 @@ describe('Workflow E2E - MCP tools', () => {
|
||||
content: [{ type: 'text', text }],
|
||||
usage: { input: 10, output: 20 },
|
||||
stopReason: 'stop',
|
||||
} as unknown as Awaited<ReturnType<typeof AgentHarness.prototype.prompt>>
|
||||
} as unknown as AssistantMessage
|
||||
})
|
||||
|
||||
await workflowService.startWorkers(TaskQueueAgent)
|
||||
@@ -244,35 +243,33 @@ describe('Workflow E2E - MCP tools', () => {
|
||||
|
||||
// For direct mode the model would call `e2e_mcp_echo` directly; simulate
|
||||
// that by executing the direct tool on the harness.
|
||||
const directSpy = vi
|
||||
.spyOn(AgentHarness.prototype, 'prompt')
|
||||
.mockImplementationOnce(async function (this: AgentHarness) {
|
||||
const tools = this.getTools()
|
||||
const echoTool = tools.find((t) => t.name === 'e2e_mcp_echo')
|
||||
if (!echoTool) {
|
||||
return {
|
||||
content: [{ type: 'text', text: 'NO_DIRECT_TOOL' }],
|
||||
usage: { input: 1, output: 1 },
|
||||
stopReason: 'stop',
|
||||
} as unknown as Awaited<ReturnType<typeof AgentHarness.prototype.prompt>>
|
||||
}
|
||||
const result = await (
|
||||
echoTool.execute as unknown as (
|
||||
id: string,
|
||||
params: Record<string, unknown>,
|
||||
) => Promise<{ content: Array<{ type: string; text?: string }> }>
|
||||
)('e2e-direct', {
|
||||
text: 'direct call',
|
||||
})
|
||||
const text = result.content
|
||||
.map((c) => ('text' in c && typeof c.text === 'string' ? c.text : ''))
|
||||
.join('\n')
|
||||
const directSpy = mockModelPrompt(async function (this: ModelScenario) {
|
||||
const tools = this.getTools()
|
||||
const echoTool = tools.find((t) => t.name === 'e2e_mcp_echo')
|
||||
if (!echoTool) {
|
||||
return {
|
||||
content: [{ type: 'text', text }],
|
||||
content: [{ type: 'text', text: 'NO_DIRECT_TOOL' }],
|
||||
usage: { input: 1, output: 1 },
|
||||
stopReason: 'stop',
|
||||
} as unknown as Awaited<ReturnType<typeof AgentHarness.prototype.prompt>>
|
||||
} as unknown as AssistantMessage
|
||||
}
|
||||
const result = await (
|
||||
echoTool.execute as unknown as (
|
||||
id: string,
|
||||
params: Record<string, unknown>,
|
||||
) => Promise<{ content: Array<{ type: string; text?: string }> }>
|
||||
)('e2e-direct', {
|
||||
text: 'direct call',
|
||||
})
|
||||
const text = result.content
|
||||
.map((c) => ('text' in c && typeof c.text === 'string' ? c.text : ''))
|
||||
.join('\n')
|
||||
return {
|
||||
content: [{ type: 'text', text }],
|
||||
usage: { input: 1, output: 1 },
|
||||
stopReason: 'stop',
|
||||
} as unknown as AssistantMessage
|
||||
})
|
||||
|
||||
const userComment = await prisma.assetComment.create({
|
||||
data: {
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
import {
|
||||
createModels,
|
||||
fauxAssistantMessage,
|
||||
fauxToolCall,
|
||||
type AssistantMessage,
|
||||
type Message,
|
||||
type Models,
|
||||
type ToolResultMessage,
|
||||
} from '@earendil-works/pi-ai'
|
||||
import { getCurrentTools } from '@earendil-works/pi-ai/utils/transcript'
|
||||
import { AssistantMessageEventStream } from '@earendil-works/pi-ai/utils/event-stream'
|
||||
import type { JsonObject } from '@earendil-works/pi-durable'
|
||||
import { vi } from 'vitest'
|
||||
|
||||
type ModelReply = {
|
||||
content: AssistantMessage['content']
|
||||
usage?: unknown
|
||||
stopReason?: AssistantMessage['stopReason']
|
||||
}
|
||||
type ScenarioTool = {
|
||||
name: string
|
||||
execute(
|
||||
id: string,
|
||||
args: Record<string, unknown>,
|
||||
...unused: unknown[]
|
||||
): Promise<{ content: ToolResultMessage['content']; details?: unknown }>
|
||||
}
|
||||
export interface ModelScenario {
|
||||
getTools(): ScenarioTool[]
|
||||
}
|
||||
class RequestTool extends Error {
|
||||
constructor(
|
||||
readonly name: string,
|
||||
readonly args: Record<string, unknown>,
|
||||
readonly id: string,
|
||||
) {
|
||||
super('Model requests a tool')
|
||||
}
|
||||
}
|
||||
|
||||
/** Mock the provider boundary. Every requested tool is executed by the real Durable runtime. */
|
||||
export function mockModelPrompt(
|
||||
scenario: (this: ModelScenario, prompt: string) => Promise<ModelReply>,
|
||||
) {
|
||||
return vi
|
||||
.spyOn(Object.getPrototypeOf(createModels()) as Models, 'streamSimple')
|
||||
.mockImplementation((_model, transcript) => {
|
||||
const stream = new AssistantMessageEventStream()
|
||||
void (async () => {
|
||||
const lastInput = transcript.messages.findLastIndex((message) => message.role === 'user')
|
||||
const round = transcript.messages.slice(lastInput + 1)
|
||||
const results = round.filter(
|
||||
(message): message is ToolResultMessage => message.role === 'toolResult',
|
||||
)
|
||||
let index = 0
|
||||
const host: ModelScenario = {
|
||||
getTools: () =>
|
||||
getCurrentTools(transcript.messages).map((tool) => ({
|
||||
name: tool.name,
|
||||
execute: async (id, args) => {
|
||||
const position = index++
|
||||
const result = results[position]
|
||||
if (!result) throw new RequestTool(tool.name, args, `${id}-${position}`)
|
||||
if (result.toolName !== tool.name)
|
||||
throw new Error(`Expected result for ${tool.name}, received ${result.toolName}`)
|
||||
return { content: result.content, details: result.details }
|
||||
},
|
||||
})),
|
||||
}
|
||||
const input = transcript.messages[lastInput]
|
||||
const prompt = input?.role === 'user' ? messageText(input) : ''
|
||||
let answer: AssistantMessage
|
||||
try {
|
||||
const reply = await scenario.call(host, prompt)
|
||||
answer = {
|
||||
...fauxAssistantMessage(reply.content),
|
||||
stopReason: reply.stopReason ?? 'stop',
|
||||
}
|
||||
} catch (error) {
|
||||
if (!(error instanceof RequestTool)) {
|
||||
console.error('Model scenario failed', error)
|
||||
stream.push({
|
||||
type: 'error',
|
||||
reason: 'error',
|
||||
error: {
|
||||
...fauxAssistantMessage(''),
|
||||
stopReason: 'error',
|
||||
errorMessage: String(error),
|
||||
},
|
||||
})
|
||||
stream.end()
|
||||
return
|
||||
}
|
||||
answer = fauxAssistantMessage(
|
||||
[
|
||||
fauxToolCall(error.name, JSON.parse(JSON.stringify(error.args)) as JsonObject, {
|
||||
id: error.id,
|
||||
}),
|
||||
],
|
||||
{ stopReason: 'toolUse' },
|
||||
)
|
||||
}
|
||||
stream.push({
|
||||
type: 'done',
|
||||
reason: answer.stopReason as 'stop' | 'length' | 'toolUse',
|
||||
message: answer,
|
||||
})
|
||||
stream.end()
|
||||
})()
|
||||
return stream
|
||||
})
|
||||
}
|
||||
function messageText(message: Message) {
|
||||
return typeof message.content === 'string'
|
||||
? message.content
|
||||
: message.content
|
||||
.filter((block) => block.type === 'text')
|
||||
.map((block) => block.text)
|
||||
.join('\n')
|
||||
}
|
||||
@@ -1,16 +1,17 @@
|
||||
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'
|
||||
import type { AssistantMessage } from '@earendil-works/pi-ai'
|
||||
import { initAgentWorkflows } from '@shumai/agent'
|
||||
import { getAssetRenderOp, readAssetOp, runOperation } from '@shumai/core/src/operations'
|
||||
import { projectService } from '@shumai/core/src/project/project'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { prisma, type User } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { workflowService, TaskQueueAgent, TaskQueueTranscode } from '@shumai/workflow-core'
|
||||
import { initAgentWorkflows } from '@shumai/agent'
|
||||
import { initTranscodeWorkflows } from '@shumai/transcode'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { projectService } from '@shumai/core/src/project/project'
|
||||
import { getAssetRenderOp, readAssetOp, runOperation } from '@shumai/core/src/operations'
|
||||
import { AgentHarness } from '@earendil-works/pi-agent-core'
|
||||
import { fileURLToPath } from 'url'
|
||||
import * as path from 'path'
|
||||
import { TaskQueueAgent, TaskQueueTranscode, workflowService } from '@shumai/workflow-core'
|
||||
import * as fs from 'fs'
|
||||
import * as path from 'path'
|
||||
import { fileURLToPath } from 'url'
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
|
||||
import { mockModelPrompt, type ModelScenario } from './model-mock'
|
||||
|
||||
const BUCKET = 'shumai-e2e-test-bucket-read-asset'
|
||||
const fixturesDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../fixtures')
|
||||
@@ -38,9 +39,7 @@ describe('Workflow E2E - read_asset', () => {
|
||||
initTranscodeWorkflows()
|
||||
initAgentWorkflows()
|
||||
|
||||
vi.spyOn(AgentHarness.prototype, 'prompt').mockImplementation(async function (
|
||||
this: AgentHarness,
|
||||
) {
|
||||
mockModelPrompt(async function (this: ModelScenario) {
|
||||
const readAsset = this.getTools().find((t) => t.name === 'read_asset') as unknown as
|
||||
ExecutableTool | undefined
|
||||
const hasRenderTool = this.getTools().some((t) => t.name === 'get_asset_render')
|
||||
@@ -49,7 +48,7 @@ describe('Workflow E2E - read_asset', () => {
|
||||
content: [{ type: 'text', text: 'MISSING_READ_ASSET' }],
|
||||
usage: { input: 1, output: 1 },
|
||||
stopReason: 'stop',
|
||||
} as unknown as Awaited<ReturnType<typeof AgentHarness.prototype.prompt>>
|
||||
} as unknown as AssistantMessage
|
||||
}
|
||||
const result = await readAsset.execute('call-1', {
|
||||
assetId: videoAssetId,
|
||||
@@ -76,7 +75,7 @@ describe('Workflow E2E - read_asset', () => {
|
||||
content: [{ type: 'text', text: summary }],
|
||||
usage: { input: 10, output: 20 },
|
||||
stopReason: 'stop',
|
||||
} as unknown as Awaited<ReturnType<typeof AgentHarness.prototype.prompt>>
|
||||
} as unknown as AssistantMessage
|
||||
})
|
||||
|
||||
await workflowService.startWorkers([TaskQueueTranscode, TaskQueueAgent])
|
||||
|
||||
Reference in New Issue
Block a user