Files
shumai/packages/agent/src/workflows/agent-autofill.ts
T
Yiling-J 35a0e82284 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
2026-11-11 16:05:18 +08:00

141 lines
4.0 KiB
TypeScript

import { getProxyType } from '@shumai/core/src/utils/mime'
import type { WorkflowTask } from '@shumai/db'
import {
ApplicationFailure,
updateTaskStatusActivity,
updateTaskUsageActivity,
} from '@shumai/workflow-core'
import {
autofillAiActivity,
createCommentActivity,
getAgentAutofillContextActivity,
getAssetActivity,
getProjectAutofillFieldsActivity,
updateAssetMetadataActivity,
} from '../activities/agent'
export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
try {
// Update status to processing
await updateTaskStatusActivity({
taskId: task.id,
status: 'processing',
})
// 1. Get Asset
const asset = await getAssetActivity(task.assetId)
if (!asset || !asset.project) {
throw ApplicationFailure.create({ message: 'Asset or project not found', nonRetryable: true })
}
const teamId = asset.project.teamId
const projectId = asset.project.id
// 2. Get Project Autofill Fields
const fields = await getProjectAutofillFieldsActivity(projectId)
if (fields.length === 0) {
await updateTaskStatusActivity({
taskId: task.id,
status: 'completed',
})
return
}
// 3. Fetch Agent Context
const context = await getAgentAutofillContextActivity({
teamId,
})
// 4. Call AI Service (inspects asset on demand via read_asset)
const mediaInfo = asset.media as PrismaJson.MediaInfo | null
const proxyType = mediaInfo?.proxyType || getProxyType(asset.mediaType, asset.name) || undefined
const duration =
(proxyType === 'video' || proxyType === 'audio') && typeof mediaInfo?.duration === 'number'
? mediaInfo.duration
: undefined
const pageCount =
proxyType === 'pdf'
? typeof mediaInfo?.metadata?.totalFrames === 'number'
? mediaInfo.metadata.totalFrames
: typeof mediaInfo?.frames === 'number'
? mediaInfo.frames
: undefined
: undefined
const aiResult = await autofillAiActivity({
taskId: task.id,
teamId,
assetId: asset.id,
assetName: asset.name,
mediaType: asset.mediaType ?? undefined,
duration,
pageCount,
projectId: asset.projectId ?? undefined,
fields: fields.map((f) => ({
id: f.key,
config: (f.config as unknown as PrismaJson.FieldConfig) ?? {},
description: f.description,
})),
context,
})
if (aiResult.usage) {
// Update Usage
await updateTaskUsageActivity({
taskId: task.id,
inputTokens: aiResult.usage.inputTokens,
outputTokens: aiResult.usage.outputTokens,
model: aiResult.usage.model,
})
}
// 6. Update Asset Metadata
const result = JSON.parse(aiResult.text)
const metadataUpdates = Object.entries(result)
.filter(([, value]) => value !== null)
.map(([key, value]) => ({
key,
value,
}))
if (metadataUpdates.length > 0) {
await updateAssetMetadataActivity({
assetId: asset.id,
metadata: metadataUpdates,
})
}
// Update status to completed
await updateTaskStatusActivity({
taskId: task.id,
status: 'completed',
})
} catch (err) {
console.error(`AgentAutofillMedia failed for task ${task.id}:`, err)
// Create error comment
try {
const payload = task.payload
await createCommentActivity({
assetId: task.assetId,
message: `Autofill failed: ${err instanceof Error ? err.message : String(err)}`,
sessionId: payload?.agent?.sessionId || task.id,
agentId: payload?.agent?.agentId || 'default',
})
} catch (commentErr) {
console.error('Failed to create error comment:', commentErr)
}
// Update status to failed
await updateTaskStatusActivity({
taskId: task.id,
status: 'failed',
output: { error: err instanceof Error ? err.message : String(err) },
})
throw err
}
}
export const agentAutofillWorkflow = agentAutofillMedia