Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 11 additions & 23 deletions apps/sim/app/api/copilot/stats/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,23 +12,11 @@ import { SIM_AGENT_API_URL_DEFAULT } from '@/lib/sim-agent'

const SIM_AGENT_API_URL = env.SIM_AGENT_API_URL || SIM_AGENT_API_URL_DEFAULT

const BodySchema = z
.object({
// Do NOT send id; messageId is the unique correlator
userId: z.string().optional(),
chatId: z.string().uuid().optional(),
messageId: z.string().optional(),
depth: z.number().int().nullable().optional(),
maxEnabled: z.boolean().nullable().optional(),
createdAt: z.union([z.string().datetime(), z.date()]).optional(),
diffCreated: z.boolean().nullable().optional(),
diffAccepted: z.boolean().nullable().optional(),
duration: z.number().int().nullable().optional(),
inputTokens: z.number().int().nullable().optional(),
outputTokens: z.number().int().nullable().optional(),
aborted: z.boolean().nullable().optional(),
})
.passthrough()
const BodySchema = z.object({
messageId: z.string(),
diffCreated: z.boolean(),
diffAccepted: z.boolean(),
})

export async function POST(req: NextRequest) {
const tracker = createRequestTracker()
Expand All @@ -43,15 +31,15 @@ export async function POST(req: NextRequest) {
if (!parsed.success) {
return createBadRequestResponse('Invalid request body for copilot stats')
}
const body = parsed.data as any

// Build outgoing payload for Sim Agent; do not include id
const { messageId, diffCreated, diffAccepted } = parsed.data as any
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

style: unnecessary type assertion - parsed.data is already properly typed

Suggested change
const { messageId, diffCreated, diffAccepted } = parsed.data as any
const { messageId, diffCreated, diffAccepted } = parsed.data

Context Used: Context - Avoid using type assertions to 'any' in TypeScript. Instead, ensure proper type definitions are used to maintain type safety. (link)


// Build outgoing payload for Sim Agent with only required fields
const payload: Record<string, any> = {
...body,
userId: body.userId || userId,
createdAt: body.createdAt || new Date().toISOString(),
messageId,
diffCreated,
diffAccepted,
}
payload.id = undefined

const agentRes = await fetch(`${SIM_AGENT_API_URL}/api/stats`, {
method: 'POST',
Expand Down
19 changes: 0 additions & 19 deletions apps/sim/lib/copilot/tools/client/workflow/build-workflow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,25 +95,6 @@ export class BuildWorkflowClientTool extends BaseClientTool {
// Populate diff preview immediately (without marking complete yet)
try {
const diffStore = useWorkflowDiffStore.getState()
// Send early stats upsert with the triggering user message id if available
try {
const { useCopilotStore } = await import('@/stores/copilot/store')
const { currentChat, currentUserMessageId, agentDepth, agentPrefetch } =
useCopilotStore.getState() as any
if (currentChat?.id && currentUserMessageId) {
fetch('/api/copilot/stats', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
chatId: currentChat.id,
messageId: currentUserMessageId,
depth: agentDepth,
maxEnabled: agentDepth >= 2 && !agentPrefetch,
diffCreated: true,
}),
}).catch(() => {})
}
} catch {}
await diffStore.setProposedChanges(result.yamlContent)
logger.info('diff proposed changes set')
} catch (e) {
Expand Down
19 changes: 0 additions & 19 deletions apps/sim/lib/copilot/tools/client/workflow/edit-workflow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,25 +151,6 @@ export class EditWorkflowClientTool extends BaseClientTool {
try {
if (!this.hasAppliedDiff) {
const diffStore = useWorkflowDiffStore.getState()
// Send early stats upsert with the triggering user message id if available
try {
const { useCopilotStore } = await import('@/stores/copilot/store')
const { currentChat, currentUserMessageId, agentDepth, agentPrefetch } =
useCopilotStore.getState() as any
if (currentChat?.id && currentUserMessageId) {
fetch('/api/copilot/stats', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
chatId: currentChat.id,
messageId: currentUserMessageId,
depth: agentDepth,
maxEnabled: agentDepth >= 2 && !agentPrefetch,
diffCreated: true,
}),
}).catch(() => {})
}
} catch {}
await diffStore.setProposedChanges(result.yamlContent)
logger.info('diff proposed changes set for edit_workflow')
this.hasAppliedDiff = true
Expand Down
63 changes: 1 addition & 62 deletions apps/sim/stores/copilot/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1685,27 +1685,6 @@ export const useCopilotStore = create<CopilotStore>()(
}).catch(() => {})
} catch {}
}

// Optimistic stats: mark aborted for the in-flight user message
try {
const { currentChat: cc, currentUserMessageId, messageMetaById } = get() as any
if (cc?.id && currentUserMessageId) {
const meta = messageMetaById?.[currentUserMessageId] || null
const agentDepth = meta?.depth
const maxEnabled = meta?.maxEnabled
fetch('/api/copilot/stats', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
chatId: cc.id,
messageId: currentUserMessageId,
...(typeof agentDepth === 'number' ? { depth: agentDepth } : {}),
...(typeof maxEnabled === 'boolean' ? { maxEnabled } : {}),
aborted: true,
}),
}).catch(() => {})
}
} catch {}
} catch {
set({ isSendingMessage: false, isAborting: false, abortController: null })
}
Expand Down Expand Up @@ -2113,47 +2092,7 @@ export const useCopilotStore = create<CopilotStore>()(

// Post copilot_stats record (input/output tokens can be null for now)
try {
const { messageMetaById } = get() as any
const meta =
(messageMetaById && (messageMetaById as any)[triggerUserMessageId || '']) || null
const agentDepth = meta?.depth ?? get().agentDepth
const maxEnabled = meta?.maxEnabled ?? (agentDepth >= 2 && !get().agentPrefetch)
const { useWorkflowDiffStore } = await import('@/stores/workflow-diff/store')
const diffState = useWorkflowDiffStore.getState() as any
const diffCreated = !!diffState?.isShowingDiff
const diffAccepted = false // acceptance may arrive earlier or later via diff store
const endMs = Date.now()
const duration = Math.max(0, endMs - startTimeMs)
const chatIdToUse = get().currentChat?.id || context.newChatId
// Prefer provided trigger user message id; fallback to last user message
let userMessageIdToUse = triggerUserMessageId
if (!userMessageIdToUse) {
const msgs = get().messages
for (let i = msgs.length - 1; i >= 0; i--) {
const m = msgs[i]
if (m.role === 'user') {
userMessageIdToUse = m.id
break
}
}
}
if (chatIdToUse) {
fetch('/api/copilot/stats', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
chatId: chatIdToUse,
messageId: userMessageIdToUse || assistantMessageId,
depth: agentDepth,
maxEnabled,
diffCreated,
diffAccepted,
duration: duration ?? null,
inputTokens: null,
outputTokens: null,
}),
}).catch(() => {})
}
// Removed: stats sending now occurs only on accept/reject with minimal payload
} catch {}
} finally {
clearTimeout(timeoutId)
Expand Down
2 changes: 0 additions & 2 deletions apps/sim/stores/workflow-diff/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -303,7 +303,6 @@ export const useWorkflowDiffStore = create<WorkflowDiffState & WorkflowDiffActio
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
chatId: currentChat.id,
messageId: triggerMessageId,
diffCreated: true,
diffAccepted: true,
Expand Down Expand Up @@ -441,7 +440,6 @@ export const useWorkflowDiffStore = create<WorkflowDiffState & WorkflowDiffActio
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
chatId: currentChat.id,
messageId: triggerMessageId,
diffCreated: true,
diffAccepted: false,
Expand Down